Problem :
When I am trying to send variable data from child component class to its parent class. I’m getting the below error
Uncaught TypeError: this.props.onChange is not a function
Solution:
Pass the values from Child Component to its Parent Component in ReactJS, I found several ways to solve this problem and we will learn all the approaches to pass the data from the child component to its parent in reactJs. make sure the handleLanguage()
the function is declared in the ParentComponent.js
file ?. or you can follow the below approach to pass value from the child component to its parent function.
Aprroach 1: using Refs and the DOM, pass data from child to its component
Step 1: Create a parent component function
In the below snippet I have created a function handleLanguage
and passed the function as props to its child component like this
<SelectLanguage onSelectLanguage={this.handleLanguage} />
So, the final version of the Parent ParentComponent.js
component looks like below snippet
Step 2 : Creating Refs
Refs are created using React.createRef()
and attached to React elements via the attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.
Step 3: Accessing Refs and pass the value to it’s parent component function onSelectLanguage()
When a ref is passed to an element in render
, a reference to the node becomes accessible at the current
the attribute of the ref.
So, the final version of the Child component SelectLanguage.js
looks like the below snippet
Conclusion:
We could pass values to the parent component from its child component via props, by calling this.props.parentMethod(value)
in the child methods. Hope you find them helpful.