0

Let say I have this Parent

const Parent = () => <ChildComponent foo={<Button>clic</Button>} />

why would this code work

class ChildComponent extends React.Component {
    render() {
        return (
            <div>
                {this.props.foo}
            </div>
        )
    }
}

but this code would not ?

class ChildComponent extends React.Component {
    constructor(props) {
        super(props)
        const ParentButton = this.props.foo
    }
    render() {
        return (
            <div>
                <ParentButton />
            </div>
        )
    }
}

I need something like the second example in order to add some event to ParentButton.

I'd like to make this example work with class defined component

Update :

Based on answer I now have a partial solution

class ChildComponent extends React.Component {
    constructor(props) {
        super(props)
        this.ParentButton = this.props.foo
    }
    render() {
        return (
            <div>
                {this.ParentButton}
            </div>
        )
    }
}
Yvain
  • 882
  • 1
  • 10
  • 27

1 Answers1

1

You're not assigning ParentButton to the ChildComponent.

What you currently have is a const floating in the constructor since const, let and var keywords are function/block scoped.

this. ParentButton = this.props.foo and succinctly <this. ParentButton > in your render function will get you what you're after.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • I mark it as answer for the scope part. as for rendering do not work. (Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.) – Yvain Jun 29 '18 at 15:32
  • @Yvain Get rid of the `{}` and render it like so `` since it's a component. – Henrik Andersson Jul 01 '18 at 03:51