Skip to content

Commit

Permalink
Add sub-component support to Require
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed May 30, 2016
1 parent 3cf4667 commit c56f175
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
6 changes: 3 additions & 3 deletions component.go
Expand Up @@ -57,7 +57,7 @@ type Component interface {
// A Factory is a Component that can construct Elements (analogous to a ReactClass or a ReactFactory).
type Factory interface {
Component
CreateElement(props Props) *Element
CreateElement(props Props, children ...*Element) *Element
}

// ReactComponent wraps a Facebook React component.
Expand Down Expand Up @@ -107,8 +107,8 @@ func FromGlobal(path ...string) *ReactComponent {
// Require loads a module the Node.js way.
// Note that this requires that the require function is present; if in the browser,
// and not in Node.js, try Browserify.
func Require(path string) *ReactComponent {
m, err := support.Require(path)
func Require(path ...string) *ReactComponent {
m, err := support.Require(path...)
if err != nil {
panic(err)
}
Expand Down
18 changes: 13 additions & 5 deletions support/support.go
Expand Up @@ -26,18 +26,26 @@ import (
// Require loads a JS object the Node.js way.
// Note that this requires that the require function is present; if in the browser,
// and not in Node.js, try Browserify.
func Require(path string) (*js.Object, error) {
func Require(path ...string) (*js.Object, error) {
require := js.Global.Get("require")

if require == js.Undefined {
return nil, errors.New("require() not defined; if this is not Node.js, give Browserify a try.")
return nil, errors.New("require() not defined; if this is not Node.js, give Browserify a try")
}

m := require.Invoke(path)
var component *js.Object

if m == js.Undefined {
for _, p := range path {
if component != nil {
component = component.Get(p)
} else {
component = require.Invoke(p)
}
}

if component == js.Undefined {
return nil, fmt.Errorf("Module %q not found", path)
}

return m, nil
return component, nil
}
2 changes: 1 addition & 1 deletion tests/component_test.go
Expand Up @@ -115,7 +115,7 @@ func TestCompositeComponents(t *testing.T) {
elem := rc.CreateElement(gr.Props{"text": "Composite Test"})
r := grt.ShallowRender(elem)

grt.Equal(t, `<div><h1>Composite Test</h1><tests.testLifecycler text="c1" /><tests.testLifecycler text="c2" /><tests.testLifecycler text="c3" /></div>`,
grt.Equal(t, `<div><h1>Composite Test</h1><tests.testLifecycler text="c1"></tests.testLifecycler><tests.testLifecycler text="c2"></tests.testLifecycler><tests.testLifecycler text="c3"></tests.testLifecycler></div>`,
r.String())

// dive into the first subcomponent
Expand Down

0 comments on commit c56f175

Please sign in to comment.