Skip to content

Commit 8205c36

Browse files
Making react work
1 parent 4ed5dd1 commit 8205c36

4 files changed

Lines changed: 83 additions & 214 deletions

File tree

playground/internal/react/elements.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ func Button(value string, props Props, onClick func()) *Element {
2525
return CreateElement(`input`, props)
2626
}
2727

28+
// =============================================================
29+
2830
type Counter struct {
2931
*Component
3032
}
@@ -65,3 +67,30 @@ func NewCounter() *Counter {
6567
})
6668
return c
6769
}
70+
71+
// =============================================================
72+
73+
// Returns a JS class (constructor) for a React component
74+
func NewReactComponentClass(renderFunc func() Node) *js.Object {
75+
reactComp := react().Get("Component")
76+
// Create a constructor function
77+
ctor := js.MakeFunc(func(this *js.Object, args []*js.Object) any {
78+
// Call React.Component constructor
79+
reactComp.Call(`call`, this)
80+
return nil
81+
})
82+
proto := ctor.Get("prototype")
83+
// Set up inheritance: ctor.prototype = Object.create(React.Component.prototype)
84+
proto.Set("__proto__", reactComp.Get("prototype"))
85+
// Set the render method on the prototype
86+
proto.Set("render", renderFunc)
87+
return ctor
88+
}
89+
90+
func NewMyComponent() *Element {
91+
MyComponentClass := NewReactComponentClass(func() Node {
92+
return Div(nil, `Hello from GopherJS (2)!`)
93+
})
94+
args := []any{MyComponentClass, nil}
95+
return &Element{Object: react().Call(`createElement`, args...)}
96+
}

playground/internal/react/react.go

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,20 +51,11 @@ func CreateElement(typ string, props Props, children ...Node) *Element {
5151

5252
func checkNode(n Node) Node {
5353
switch c := n.(type) {
54-
case Renderable:
55-
return &Element{Object: react().Call(`createElement`, c.Render)}
5654
case *Element, string, int, float64:
5755
return c
56+
case interface{ Interface() any }:
57+
return &Element{Object: react().Call(`createElement`, c.Interface())}
5858
default:
5959
panic(fmt.Errorf(`unsupported child type %T`, c))
6060
}
6161
}
62-
63-
func SimpleElement() *Element {
64-
c := react().Get(`Component`).New()
65-
c.Set(`render`, func() Node {
66-
return CreateElement(`div`, nil, `Hello World!`)
67-
})
68-
69-
return &Element{Object: react().Call(`createElement`, c.Get(`render`))}
70-
}

playground/playground.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,7 @@ func main() {
2121
root := react.CreateRoot(`root`)
2222
//root.Render(react.CreateElement(`div`, nil, `Hello World!`))
2323

24-
root.Render(react.NewCounter())
24+
//root.Render(react.NewCounter())
25+
26+
root.Render(react.NewMyComponent())
2527
}

0 commit comments

Comments
 (0)