I try to pass argument from child component to parent. P.S. Snippet below doesn't work if somebody fix this, it would be really great.
class Parent extends React.Component {
suggestionClick(id) {
console.log(this.props, id); // {props Object} , undefined
}
render(){
return (
<ChildComponent click={this.suggestionClick.bind(this)} />
);
}
}
const ChildComponent = ({ click }) => (
<SubChildComponent id="1" click={() => click()} />
);
const SubChildComponent = ({ click, id }) => (
<div className="subsubcomponent" click={() => click(id)} />
);
ReactDOM.render(
<Parent />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
class Parent extends React.Component {
suggestionClick(id) {
alert(id);
console.log(this.props, id); // {props Object} , undefined
}
render(){
return (
<ChildComponent click={this.suggestionClick.bind(this)} />
);
}
}
const ChildComponent = ({ click }) => (
<SubChildComponent id="1" click={click} />
);
const SubChildComponent = ({ click, id }) => (
<button className="subsubcomponent" onClick={() => click(id)}>click me</button>
);
ReactDOM.render(
<Parent />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
This is because you are not passing the value from ChildComponent to parent component, here:
<SubChildComponent id="1" click={() => click()} />
Use this:
<SubChildComponent id="1" click={(id) => click(id)} />
Or Simply:
<SubChildComponent id="1" click={click} />
Another change is replace click with onClick inside SubChildComponent.
Working Code:
class Parent extends React.Component {
suggestionClick(id) {
console.log(this.props, id); // {props Object} , undefined
}
render(){
return (
<ChildComponent click={this.suggestionClick.bind(this)} />
);
}
}
const ChildComponent = ({ click }) => (
<SubChildComponent id="1" click={(id) => click(id)} />
);
const SubChildComponent = ({ click, id }) => (
<div className="subsubcomponent" onClick={() => click(id)}>Click</div>
);
ReactDOM.render(
<Parent />,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With