How to call child component method from parent?
See original GitHub issueChild.js
import s from './Child.css';
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1 ref="hello">Hello</h1>
);
}
}
export default withStyles(s)(Child);
Parent.js
class Parent extends Component {
render() {
onClick() {
this.refs.child.getAlert() // undefined
}
return (
<div>
<Child ref="child" />
<button onClick={this.onClick.bind(this)}>Click</button>
</div>
);
}
}
Issue Analytics
- State:
- Created 7 years ago
- Reactions:60
- Comments:41 (4 by maintainers)
Top Results From Across the Web
Call child method from parent - Stack Overflow
Create a boolean variable in the state in the parent class. Update this when you want to call a function. · Create a...
Read more >Call child's function from a Parent component in React
Call child's function from a Parent component in React # · Wrap the Child component in a forwardRef . · Use the useImperativeHandle...
Read more >How To Call A Child Function From A Parent Component In ...
Method #1 - Use the useImperativeHandle hook to call a child function · Declare the function you want to expose inside the useImperativeHandle ......
Read more >How To Call Child Function From Parent Component In React
One way to call a child component's function from its parent is with the help of the useRef hook. Here's the gist of...
Read more >Call Child Function from Parent Component in React
We can call methods or functions located inside a child component simply using references which is supported on class components and recently on ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
For example you can use Refs to Components approach like so:
Demo: https://jsfiddle.net/frenzzy/z9c46qtv/
This is antipattern!