Good day. I'm building a tree of components and want to use functions of root component in other components of tree. I throw function reference through all tree.
Also I use the object if me need get value from the function in not root componet.
Can you help me?
Can you show me how to do this as HOC ?
If it will be not so hard for you show examples on my code.
import React from 'react';
class Page extends React.Component{
Answer = {
value : ''
}
doSomething(){
console.log(this.Answer.value);
console.log('Ready!');
}
render(){
return(
<div>
<div>
<Body
ParentFunc={()=>this.doSomething()}
ParentParameters={this.Answer}
/>
</div>
</div>
)
}
}
export default Page
class Body extends React.Component{
render(){
const{
ParentFunc,
ParentParameters
} = this.props
return(
<div>
<div>
<SomeComponent
ParentFunc={()=>ParentFunc()}
ParentParameters={ParentParameters}
/>
</div>
</div>
)
}
}
class SomeComponent extends React.Component{
getAnswer(){
const{
ParentFunc,
ParentParameters
} = this.props
ParentParameters.value = 'Some text'
ParentFunc()
}
render(){
return(
<div onClick={()=>this.getAnswer()}>
We can?
</div>
)
}
}
I don't believe a Higher Order Component alone will solve your basic issue of prop drilling. A React Context would be a better fit for providing values and functions generally to "want to use functions of root component in other components of tree".
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
In a typical React application, data is passed top-down (parent to
child) via props, but such usage can be cumbersome for certain types
of props (e.g. locale preference, UI theme) that are required by many
components within an application. Context provides a way to share
values like these between components without having to explicitly pass
a prop through every level of the tree.
Start by creating your Context and Provider component:
const QnAContext = React.createContext({
answer: {
value: ""
},
doSomething: () => {}
});
const QnAProvider = ({ children }) => {
const answer = {
value: ""
};
const doSomething = () => {
console.log(answer.value);
console.log("Ready!");
};
return (
<QnAContext.Provider value={{ answer, doSomething }}>
{children}
</QnAContext.Provider>
);
};
Render QnAProvider in your app somewhere wrapping the React subtree you want to have access to the values being provided:
<QnAProvider>
<Page />
</QnAProvider>
Consuming the Context:
Class-based components consume contexts via the render props pattern.
<QnAContext.Consumer>
{({ answer, doSomething }) => (
<SomeComponent doSomething={doSomething} answer={answer}>
We can?
</SomeComponent>
)}
</QnAContext.Consumer>
Functional components can use the useContext React hook
const SomeComponent = ({ children }) => {
const { answer, doSomething } = useContext(QnAContext);
getAnswer = () => {
answer.value = "Some text";
doSomething();
};
return <div onClick={this.getAnswer}>{children}</div>;
};
Here is where using a Higher Order Component may become useful. You can abstract the QnAContext.Consumer render props pattern into a HOC:
const withQnAContext = (Component) => (props) => (
<QnAContext.Consumer>
{(value) => <Component {...props} {...value} />}
</QnAContext.Consumer>
);
Then you can decorate components you want to have the context values injected into.
const DecoratedSomeComponent = withQnAContext(SomeComponent);
...
<DecoratedSomeComponent>We can with HOC?</DecoratedSomeComponent>
Note: The point of doing all this was to move the values and functions that were previously defined in Page into the Context, so they are no longer passed from Page though Body to SomeComponent (or any other children components).
Demo
Sandbox Code:
const QnAContext = React.createContext({
answer: {
value: ""
},
doSomething: () => {}
});
const QnAProvider = ({ children }) => {
const answer = {
value: ""
};
const doSomething = () => {
console.log(answer.value);
console.log("Ready!");
};
return (
<QnAContext.Provider value={{ answer, doSomething }}>
{children}
</QnAContext.Provider>
);
};
const withQnAContext = (Component) => (props) => (
<QnAContext.Consumer>
{(value) => <Component {...props} {...value} />}
</QnAContext.Consumer>
);
class SomeComponent extends React.Component {
getAnswer = () => {
const { doSomething, answer } = this.props;
answer.value = "Some text";
doSomething();
};
render() {
return (
<button type="button" onClick={this.getAnswer}>
{this.props.children}
</button>
);
}
}
const DecoratedSomeComponent = withQnAContext(SomeComponent);
class Body extends React.Component {
render() {
return (
<div>
<div>
<QnAContext.Consumer>
{({ answer, doSomething }) => (
<SomeComponent doSomething={doSomething} answer={answer}>
We can?
</SomeComponent>
)}
</QnAContext.Consumer>
</div>
<div>
<DecoratedSomeComponent>We can with HOC?</DecoratedSomeComponent>
</div>
</div>
);
}
}
class Page extends React.Component {
render() {
return (
<div>
<div>
<Body />
</div>
</div>
);
}
}
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<QnAProvider>
<Page />
</QnAProvider>
</div>
);
}
Based on your current code I am making the assumption that Body does not modify the values of ParentFunc and ParentParameters before passing them down to SomeComponent.
You have a hierarchy
<Page>
<Body>
<SomeComponent>
</Body>
</Page>
and you want to pass props from Page to SomeComponent without going through Body.
You can do this using children
children is a special prop representing the JSX child elements of the component. We make it so that Body renders the children that it got through props:
class Body extends React.Component{
render() {
return(
<div>
<div>
{this.props.children}
</div>
</div>
)
}
}
We set that children prop by using a <SomeComponent/> element inside of the <Body>:
render() {
return (
<div>
<div>
<Body>
<SomeComponent
ParentFunc={() => this.doSomething()}
ParentParameters={this.Answer}
/>
</Body>
</div>
</div>
);
}
Note that you cannot directly modify the value that you got from the parent, which is what you were doing with ParentParameters.value = 'Some text'. If you want to update the state of the parent then you need to do that through your callback function props. So your code should look something like this:
import React from "react";
class Body extends React.Component {
render() {
return (
<div>
<div>{this.props.children}</div>
</div>
);
}
}
class SomeComponent extends React.Component {
state = {
showAnswer: false
};
onClick() {
// update answer in parent
this.props.setAnswer("Some text");
// change state to reveal answer
this.setState({ showAnswer: true });
}
render() {
return (
<div>
{this.state.showAnswer && <div>Answer is: {this.props.answer}</div>}
<div onClick={() => this.onClick()}>We can?</div>
</div>
);
}
}
class Page extends React.Component {
state = {
value: ""
};
render() {
return (
<div>
<div>
<Body>
<SomeComponent
answer={this.state.value}
setAnswer={(answer) => this.setState({ value: answer })}
/>
</Body>
</div>
</div>
);
}
}
export default Page;
Related
I'm trying to extract a reference from a child and make it available elsewhere in my app. Here is my parent component:
class App extends React.Component {
setRef = (ref) => {
this.mapReference = ref
console.log(this.mapReference);
}
render () {
return (
<div className="App">
<Map setRef={this.setRef} />
<UIWindow mapRef={this.mapReference} />
</div>
)
}
}
export default App;
And the reference is coming from the callback setRef function in the <Map /> component, which looks like this:
class Map extends React.Component {
componentDidMount(){
this.props.setRef(this.refs.map.leafletElement)
}
render () {
const { position, zoom } = this.props
return(
<LeafletMap
className="sidebar-map"
center={position} zoom={zoom} id="mapId"
ref={"map"}
>
</LeafletMap>
)
}
}
The console.log statement in my <App /> is returning my reference correctly, which is a map object. So my reference is being correctly passed from the child (<Map />) to the parent (<App />), and is available there. As you can see, I am trying to pass that reference back down into my <UIWindow /> to have access to it there.
class UIWindow extends React.Component {
componentDidMount() {
console.log(this.props.mapRef);
}
render () {
return(
<div className="UIWindow">
<Header />
<ControlLayer />
</div>
)
}
}
export default UIWindow;
But within my UIWindow, this.props.mapRef is undefined - the log statement is giving undefined. I'm not sure what I'm missing here. If its defined in the parent App, why is it undefined in the child? Is this not the correct way to pass a reference between siblings?
React does not know what this.mapReference is when it re-renders since the variable was tied to that instance of the class. You can declare state and pass it to the child:
class App extends React.Component {
state = { mapReference: null }
setRef = ref => {
this.setState({ mapReference: ref }, () =>
console.log(this.state.mapReference)
); //Log once reference is updated
};
render () {
return (
<div className="App">
<Map setRef={this.setRef} />
{this.state.mapReference && <UIWindow mapRef={this.state.mapReference} />}
</div>
)
}
}
export default App;
-I am using function component.
-for now I am using 3 components here, from that One is parent component and another 2 are child components.
-I need to access one child component methods or state to another child methods. I already done with class components with CreateRef but for now I need to use with function components but I am getting Null inside 'ref.current'.
export function SideBySideList(props) {
const ref = React.createRef();
//this is call inside ListPage after sucess
function updateRightList(id) {
ref.current.state.actualSearchedModel.Id = id
ref.current.fetchDataAndUpdate();
}
function itemClicked(id) {
updateRightList(id);
}
return (
<>
<div className="col-12 no-padding">
<div className={props.leftListLayoutClass}>
<ListPage
updateRightList={updateRightList}
/>
</div>
<div className={props.rightListLayoutClass}>
<ListPage
ref={ref}
/>
</div>
</div>
<>
);
}
According to the official documentation:
You may not use the ref attribute on function components because they
don’t have instances
So if your ListPage is functional component, you have to convert it to the class component. Or your ref must refer to the DOM element inside of ListPage.
function ListPage ({ref}) {
return <div ref={ref}>Hello!</div>
}
UPDATED:
function ParentComponent () {
const [state, setState] = React.useState(null);
const onChildMount = React.useCallback((dataFromChild) => {
setState(dataFromChild);
});
return (
<div>
<pre>{JSON.stringify(state, null, 2)}</pre>
<ChildComponent onMount={onChildMount} />
</div>
)
}
function ChildComponent (props) {
const thisShouldBePassedToTheParent = "from child with love";
React.useEffect(() => {
props.onMount(thisShouldBePassedToTheParent);
}, []);
return (
<div>child component</div>
)
}
ReactDOM.render(<ParentComponent />, document.querySelector("#root"));
<script src="https://unpkg.com/react#16.9.0/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
With functional components you can use refs like this:
// Import our hooks
import React, { useRef, useEffect } from 'react';
// create our ref
const myInput = useRef();
// This is equivalent to our componentDidMount, this will focus
useEffect(() => myInput.current && myInput.current.focus());
// Parse our ref to our textField
<Textfield inputRef={myInput} />
Here you can read docs https://reactjs.org/docs/hooks-reference.html#useref
Also you may use refs like this directly:
<TextField inputRef={input => input && input.focus()} />
You can read full Article here: https://medium.com/javascript-in-plain-english/react-refs-both-class-and-functional-components-76b7bce487b8
If someone looking for solution where Parent is class component and Child is functional component, and want to get data from child (state, function)
Class component:
class Parent extends React.Component {
constructor(){
this.setReferenceToElement = element => {
this.fromChild = element;
}
}
handleClick(){
console.log(this.fromChild());
}
render(){
return (
<div>
<Child setRef={this.setReferenceToElement} />
<button onClick={handleClick}> Get state from child </button>
</div>
)
}
}
Functional component:
function Child(props){
// ... it has some state
props.setRef(state => state);
return <div> Test </div>
}
I'm trying to send data from a child component to it's parent as follow:
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguageCode: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9" >
<SelectLanguage onSelectLanguage={this.handleLanguage}/>
</div>
);
});
and here is the child component:
export const SelectLanguage = React.createClass({
getInitialState: function(){
return{
selectedCode: '',
selectedLanguage: '',
};
},
handleLangChange: function (e) {
var lang = this.state.selectedLanguage;
var code = this.state.selectedCode;
this.props.onSelectLanguage({selectedLanguage: lang});
this.props.onSelectLanguage({selectedCode: code});
},
render() {
var json = require("json!../languages.json");
var jsonArray = json.languages;
return (
<div >
<DropdownList ref='dropdown'
data={jsonArray}
value={this.state.selectedLanguage}
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
What I need is to get the selected value by user in the parent component. I'm getting this error:
Uncaught TypeError: this.props.onSelectLanguage is not a function
Can anyone help me to find the problem?
P.S. The child component is creating a dropdown from a json file, and I need the dropdown list to show both elements of the json array next to each other(like: "aaa,english" as the first choice!)
{
"languages":[
[
"aaa",
"english"
],
[
"aab",
"swedish"
],
}
This should work. While sending the prop back you are sending that as an object rather send that as a value or alternatively use it as an object in the parent component. Secondly you need to format your json object to contain name value pairs and use valueField and textField attribute of DropdownList
Short Answer
Parent:
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
Child:
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
Detailed:
EDIT:
Considering React.createClass is deprecated from v16.0 onwards, It is better to go ahead and create a React Component by extending React.Component. Passing data from child to parent component with this syntax will look like
Parent
class ParentComponent extends React.Component {
state = { language: '' }
handleLanguage = (langValue) => {
this.setState({language: langValue});
}
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
)
}
}
Child
var json = require("json!../languages.json");
var jsonArray = json.languages;
export class SelectLanguage extends React.Component {
state = {
selectedCode: '',
selectedLanguage: jsonArray[0],
}
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
render() {
return (
<div>
<DropdownList ref={(ref) => this.dropdown = ref}
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
}
Using createClass syntax which the OP used in his answer
Parent
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguage: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
);
});
Child
var json = require("json!../languages.json");
var jsonArray = json.languages;
export const SelectLanguage = React.createClass({
getInitialState: function() {
return {
selectedCode: '',
selectedLanguage: jsonArray[0],
};
},
handleLangChange: function () {
var lang = this.refs.dropdown.value;
this.props.onSelectLanguage(lang);
},
render() {
return (
<div>
<DropdownList ref='dropdown'
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
JSON:
{
"languages":[
{
"code": "aaa",
"lang": "english"
},
{
"code": "aab",
"lang": "Swedish"
},
]
}
To pass data from child component to parent component
In Parent Component:
getData(val){
// do not forget to bind getData in constructor
console.log(val);
}
render(){
return(<Child sendData={this.getData}/>);
}
In Child Component:
demoMethod(){
this.props.sendData(value);
}
Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component
in Parent Function Component we will have :
import React, { useState } from "react";
then
const [childData, setChildData] = useState("");
and passing setChildData (which do a job similar to this.setState in Class Components) to Child
return( <ChildComponent passChildData={setChildData} /> )
in Child Component first we get the receiving props
function ChildComponent(props){ return (...) }
then you can pass data anyhow like using a handler function
const functionHandler = (data) => {
props.passChildData(data);
}
in React v16.8+ function component, you can use useState() to create a function state that lets you update the parent state, then pass it on to child as a props attribute, then inside the child component you can trigger the parent state function, the following is a working snippet:
const { useState , useEffect } = React;
function Timer({ setParentCounter }) {
const [counter, setCounter] = React.useState(0);
useEffect(() => {
let countersystem;
countersystem = setTimeout(() => setCounter(counter + 1), 1000);
return () => {
clearTimeout(countersystem);
};
}, [counter]);
return (
<div className="App">
<button
onClick={() => {
setParentCounter(counter);
}}
>
Set parent counter value
</button>
<hr />
<div>Child Counter: {counter}</div>
</div>
);
}
function App() {
const [parentCounter, setParentCounter] = useState(0);
return (
<div className="App">
Parent Counter: {parentCounter}
<hr />
<Timer setParentCounter={setParentCounter} />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent.
In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.
I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.
ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
export function ParentComponent(){
const [isParentData, setIsParentData] = useState(True);
return (
<p>is this a parent data?: {isParentData}</p>
<ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
);
}
ChildComponent.js
import React from 'react';
export function ChildComponent(props){
return (
<button onClick={() => {props.sendToParent(False)}}>Update</button>
<p>The state of isParentData is {props.toChild}</p>
);
};
I found the approach how to get data from child component in parents when i need it.
Parent:
class ParentComponent extends Component{
onSubmit(data) {
let mapPoint = this.getMapPoint();
}
render(){
return (
<form onSubmit={this.onSubmit.bind(this)}>
<ChildComponent getCurrentPoint={getMapPoint => {this.getMapPoint = getMapPoint}} />
<input type="submit" value="Submit" />
</form>
)
}
}
Child:
class ChildComponent extends Component{
constructor(props){
super(props);
if (props.getCurrentPoint){
props.getCurrentPoint(this.getMapPoint.bind(this));
}
}
getMapPoint(){
return this.Point;
}
}
This example showing how to pass function from child component to parent and use this function to get data from child.
from child component to parent component as below
parent component
class Parent extends React.Component {
state = { message: "parent message" }
callbackFunction = (childData) => {
this.setState({message: childData})
},
render() {
return (
<div>
<Child parentCallback = {this.callbackFunction}/>
<p> {this.state.message} </p>
</div>
);
}
}
child component
class Child extends React.Component{
sendBackData = () => {
this.props.parentCallback("child message");
},
render() {
<button onClick={sendBackData}>click me to send back</button>
}
};
I hope this work
Found a great and easy way to do this with input recently.
Essentially I just useState and then set onChange as a prop to the child comp it takes "value" as an argument and puts it into the useState "setVal" boom I got state change child -> parent every time
const Parent = () => {
const [val, setVal] = useState("initial value")
return(
<>
<Child onChange={(value)=> setVal(value)}/>
<div>{val}</div>
</>
)
};
export default Parent;
const Child = (props) => {
return(
<button onClick={() => props.onChange("your value here") }>
)
}
Here I am trying to explain in simplest way:
I am updating the Parent Component counter from the Child Component.
Parent Component (PropsApp.jsx)
import React, { useState } from 'react'
import Child from './Child'
export default function PropsApp(){
const [counter, setCounter] = useState(0)
const updateMyCounter = () => {
setCounter(counter + 1)
}
return(
<>
<hr></hr>
<h1>This is Parent</h1>
<h2>{counter}</h2>
<Child updateParent={updateMyCounter} />
</>
)
}
Child Component (Child.jsx)
export default function Child(props){
return(
<>
<hr></hr>
<h1>This is Child</h1>
<button
onClick={props.updateParent}
>
Update Parent Component
</button>
</>
)
}
Click on the Update Parent Component and see the magic
React.createClass method has been deprecated in the new version of React, you can do it very simply in the following way make one functional component and another class component to maintain state:
Parent:
const ParentComp = () => {
getLanguage = (language) => {
console.log('Language in Parent Component: ', language);
}
<ChildComp onGetLanguage={getLanguage}
};
Child:
class ChildComp extends React.Component {
state = {
selectedLanguage: ''
}
handleLangChange = e => {
const language = e.target.value;
thi.setState({
selectedLanguage = language;
});
this.props.onGetLanguage({language});
}
render() {
const json = require("json!../languages.json");
const jsonArray = json.languages;
const selectedLanguage = this.state;
return (
<div >
<DropdownList ref='dropdown'
data={jsonArray}
value={tselectedLanguage}
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
};
The idea is to send a callback to the child which will be called to give the data back
A complete and minimal example using functions:
App will create a Child which will compute a random number and send it back directly to the parent, which will console.log the result
const Child = ({ handleRandom }) => {
handleRandom(Math.random())
return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>
To pass data from a child component to a Parent component in React:
Pass a function to the child from the parent that receives values.
When the values change in the child component call the function
with the updated values.
e.g.
const Parent = () => {
const handleChange = values => {
alert(JSON.stringify(values) );
//do something with the values
}
return (
<Child handleChange={handleChange} />
);
}
const Child = ({handleChange}) => {
return (
<button onClick={()=> handleChange('values you wish to pass') }}></button>
);
}
NB: As of react 16 I would recommend using functional components in almost all cases.
You can even avoid the function at the parent updating the state directly
In Parent Component:
render(){
return(<Child sendData={ v => this.setState({item: v}) } />);
}
In the Child Component:
demoMethod(){
this.props.sendData(value);
}
Pass data from child to parent Component using Callback
You need to pass from parent to child callback function, and then call it in the child.
Parent Component:-TimeModal
handleTimeValue = (timeValue) => {
this.setState({pouringDiff: timeValue});
}
<TimeSelection
prePourPreHours={prePourPreHours}
setPourTime={this.setPourTime}
isPrePour={isPrePour}
isResident={isResident}
isMilitaryFormatTime={isMilitaryFormatTime}
communityDateTime={moment(communityDT).format("MM/DD/YYYY hh:mm A")}
onSelectPouringTimeDiff={this.handleTimeValue}
/>
Note:- onSelectPouringTimeDiff={this.handleTimeValue}
In the Child Component call props when required
componentDidMount():void{
// Todo use this as per your scenrio
this.props.onSelectPouringTimeDiff(pouringDiff);
}
You are passing a wrong function to child component and your parent class doesn't have handleLanguage function. You can pass like this instead: <SelectLanguage onSelectLanguage={this.handleLanguageChange}/>. I think if a function is absent in a class its would would be None.
your parent component should be like this :
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
);
}
Best way to pass data from child to parent component
child component
handleLanguageCode=()=>(langValue) {
this.props.sendDatatoParent(langValue)
}
Parent
<Parent sendDatatoParent={ data => this.setState({item: data}) } />;
import { useEffect, useState } from "react";
export default function App() {
const data = (data) => {
console.log("data", data);
};
const myData = {
name: "hi this is my data"
};
return <Form onSubmit={data} myDatasa={myData} />;
}
const Form = (props) => {
console.log("myData", props.myDatasa.name);
const [choreDesc, setChoreDesc] = useState();
const handleSubmit = (e) => {
e.preventDefault();
props.onSubmit(choreDesc);
};
const handlechange = (e) => {
setChoreDesc(e.target.value);
};
return (
<form
onSubmit={(e) => {
handleSubmit(e);
}}
>
<label>Chore description:</label>
<br />
<input
name="choreDesc"
type="text"
value={choreDesc}
onChange={handlechange}
/>
<br />
<input type="submit" value="Add Log" />
</form>
);
};
```
Passing Data between Parent and Child Component in React Hook
Passing the function to child,
and wait child passing back the value by calling parent's function
parent (../app.js)
import MyCOMP from "../component/MyCOMP"; //import child component
export default function MyMainPage() {
return(
<>
<MyCOMP
//pass function to child and wait child passback the changed value
// 1.Click child component passing function to child
ParentFunction={(x)=>{
console.log('Child Pass Back Value',x)
// 3. Parent received data
// after you get the value change you can ultilize another function, useEffect or useState
}}/>
</>
)
}
child (../component/MyCOMP.js)
export default function MyCOMP({ParentFunction}){
return(
<>
<button onClick={()=>{
// 2. Child passing back value to parent
ParentFunction("Child reply ANSWER is ","fm 99.8");}}>Click Me</button>
</>
)
}
Result
after click the button, parent class show "fm 99.8" sting value (the
child's value)
Please comment below, if it help you, or you got another idea
I'm using Higher Order Components to decorate my components.
const HOC = (WrappedComponent) => (props) => {
return (
<span>
<p>HOC Comp</p>
<WrappedComponent {...props}/>
</span>
)
}
I do like this pattern explained here: React Higher Order Components in depth
However I have a problem because the HOC causing React to recreate my component tree instead of updating the tree. This is nicely explained here React Reconciliation. HOC returns an anonymous function whereby React doesn't know it is actually rendering the same component. This is bad for performance and makes my input field lose focus.
How could I use HOC components without React recreating my tree on every render()?
Example code:
class Input extends React.Component {
componentWillMount() {
console.log('input component will mount');
}
componentWillUnmount() {
console.log('input component will unmount');
}
render() {
return (
<span>
<input value={this.props.value} onChange={this.props.onChange}/>
</span>
);
}
}
const HOC = (WrappedComponent) => {
const Help = (props) => {
return (
<span>
<WrappedComponent {...props}/>
<p>{props.help}</p>
</span>
)
};
return Help;
}
class MyComponent extends React.Component {
constructor (props) {
super(props);
this.state = {value : 'start value'}
}
onChange(event) {
this.setState({value : event.target.value});
}
render() {
const Element = HOC(Input);
return (
<span>
<Element
value={this.state.value}
onChange={this.onChange.bind(this)}
/>
</span>
)
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('container')
);
See Fiddle example (see in your browser's console to see the mount and unmount logs from the input component every time you change the input and lose your focus)
You don't have to create Element in the render function. Instead you can create it in the constructor:
class MyComponent extends React.Component {
constructor (props) {
super(props);
this.state = {value : 'start value'};
this.element = HOC(Input);
}
...
And use it in your render function like this:
<span>
<this.element
value={this.state.value}
onChange={this.onChange.bind(this)}
/>
</span>
If needed you can update this.element in componentWillReceiveProps() or componentWillUpdate().
UPDATE: fiddle
This is the way how I extended a functional component with a controlled input element via children and it does not lose focus.
/* import React, { Fragment, useState } from 'react' */
const { Fragment, useState } = React
/* HOC */
const withInput = Base => (props) => {
const [inputValue, setValue] = useState()
return <Base children={
<Fragment>
{props.children}<br />
<input
value={inputValue}
onChange={({ target: { value }}) => setValue(value)}
placeholder="input from hoc" /><br />
<span>inputValue: {inputValue}</span>
</Fragment>
} />
}
/* Component */
const MyComponent = ({children}) => (
<span>
<span>own elements</span><br />
{children}
</span>
)
const MyComponentWithInput = withInput(MyComponent)
ReactDOM.render(<MyComponentWithInput>passed children</MyComponentWithInput>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I'm trying to send data from a child component to it's parent as follow:
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguageCode: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9" >
<SelectLanguage onSelectLanguage={this.handleLanguage}/>
</div>
);
});
and here is the child component:
export const SelectLanguage = React.createClass({
getInitialState: function(){
return{
selectedCode: '',
selectedLanguage: '',
};
},
handleLangChange: function (e) {
var lang = this.state.selectedLanguage;
var code = this.state.selectedCode;
this.props.onSelectLanguage({selectedLanguage: lang});
this.props.onSelectLanguage({selectedCode: code});
},
render() {
var json = require("json!../languages.json");
var jsonArray = json.languages;
return (
<div >
<DropdownList ref='dropdown'
data={jsonArray}
value={this.state.selectedLanguage}
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
What I need is to get the selected value by user in the parent component. I'm getting this error:
Uncaught TypeError: this.props.onSelectLanguage is not a function
Can anyone help me to find the problem?
P.S. The child component is creating a dropdown from a json file, and I need the dropdown list to show both elements of the json array next to each other(like: "aaa,english" as the first choice!)
{
"languages":[
[
"aaa",
"english"
],
[
"aab",
"swedish"
],
}
This should work. While sending the prop back you are sending that as an object rather send that as a value or alternatively use it as an object in the parent component. Secondly you need to format your json object to contain name value pairs and use valueField and textField attribute of DropdownList
Short Answer
Parent:
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
Child:
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
Detailed:
EDIT:
Considering React.createClass is deprecated from v16.0 onwards, It is better to go ahead and create a React Component by extending React.Component. Passing data from child to parent component with this syntax will look like
Parent
class ParentComponent extends React.Component {
state = { language: '' }
handleLanguage = (langValue) => {
this.setState({language: langValue});
}
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
)
}
}
Child
var json = require("json!../languages.json");
var jsonArray = json.languages;
export class SelectLanguage extends React.Component {
state = {
selectedCode: '',
selectedLanguage: jsonArray[0],
}
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
render() {
return (
<div>
<DropdownList ref={(ref) => this.dropdown = ref}
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
}
Using createClass syntax which the OP used in his answer
Parent
const ParentComponent = React.createClass({
getInitialState() {
return {
language: '',
};
},
handleLanguage: function(langValue) {
this.setState({language: langValue});
},
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
);
});
Child
var json = require("json!../languages.json");
var jsonArray = json.languages;
export const SelectLanguage = React.createClass({
getInitialState: function() {
return {
selectedCode: '',
selectedLanguage: jsonArray[0],
};
},
handleLangChange: function () {
var lang = this.refs.dropdown.value;
this.props.onSelectLanguage(lang);
},
render() {
return (
<div>
<DropdownList ref='dropdown'
data={jsonArray}
valueField='lang' textField='lang'
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
});
JSON:
{
"languages":[
{
"code": "aaa",
"lang": "english"
},
{
"code": "aab",
"lang": "Swedish"
},
]
}
To pass data from child component to parent component
In Parent Component:
getData(val){
// do not forget to bind getData in constructor
console.log(val);
}
render(){
return(<Child sendData={this.getData}/>);
}
In Child Component:
demoMethod(){
this.props.sendData(value);
}
Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component
in Parent Function Component we will have :
import React, { useState } from "react";
then
const [childData, setChildData] = useState("");
and passing setChildData (which do a job similar to this.setState in Class Components) to Child
return( <ChildComponent passChildData={setChildData} /> )
in Child Component first we get the receiving props
function ChildComponent(props){ return (...) }
then you can pass data anyhow like using a handler function
const functionHandler = (data) => {
props.passChildData(data);
}
in React v16.8+ function component, you can use useState() to create a function state that lets you update the parent state, then pass it on to child as a props attribute, then inside the child component you can trigger the parent state function, the following is a working snippet:
const { useState , useEffect } = React;
function Timer({ setParentCounter }) {
const [counter, setCounter] = React.useState(0);
useEffect(() => {
let countersystem;
countersystem = setTimeout(() => setCounter(counter + 1), 1000);
return () => {
clearTimeout(countersystem);
};
}, [counter]);
return (
<div className="App">
<button
onClick={() => {
setParentCounter(counter);
}}
>
Set parent counter value
</button>
<hr />
<div>Child Counter: {counter}</div>
</div>
);
}
function App() {
const [parentCounter, setParentCounter] = useState(0);
return (
<div className="App">
Parent Counter: {parentCounter}
<hr />
<Timer setParentCounter={setParentCounter} />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent.
In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.
I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.
ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
export function ParentComponent(){
const [isParentData, setIsParentData] = useState(True);
return (
<p>is this a parent data?: {isParentData}</p>
<ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
);
}
ChildComponent.js
import React from 'react';
export function ChildComponent(props){
return (
<button onClick={() => {props.sendToParent(False)}}>Update</button>
<p>The state of isParentData is {props.toChild}</p>
);
};
I found the approach how to get data from child component in parents when i need it.
Parent:
class ParentComponent extends Component{
onSubmit(data) {
let mapPoint = this.getMapPoint();
}
render(){
return (
<form onSubmit={this.onSubmit.bind(this)}>
<ChildComponent getCurrentPoint={getMapPoint => {this.getMapPoint = getMapPoint}} />
<input type="submit" value="Submit" />
</form>
)
}
}
Child:
class ChildComponent extends Component{
constructor(props){
super(props);
if (props.getCurrentPoint){
props.getCurrentPoint(this.getMapPoint.bind(this));
}
}
getMapPoint(){
return this.Point;
}
}
This example showing how to pass function from child component to parent and use this function to get data from child.
from child component to parent component as below
parent component
class Parent extends React.Component {
state = { message: "parent message" }
callbackFunction = (childData) => {
this.setState({message: childData})
},
render() {
return (
<div>
<Child parentCallback = {this.callbackFunction}/>
<p> {this.state.message} </p>
</div>
);
}
}
child component
class Child extends React.Component{
sendBackData = () => {
this.props.parentCallback("child message");
},
render() {
<button onClick={sendBackData}>click me to send back</button>
}
};
I hope this work
Found a great and easy way to do this with input recently.
Essentially I just useState and then set onChange as a prop to the child comp it takes "value" as an argument and puts it into the useState "setVal" boom I got state change child -> parent every time
const Parent = () => {
const [val, setVal] = useState("initial value")
return(
<>
<Child onChange={(value)=> setVal(value)}/>
<div>{val}</div>
</>
)
};
export default Parent;
const Child = (props) => {
return(
<button onClick={() => props.onChange("your value here") }>
)
}
Here I am trying to explain in simplest way:
I am updating the Parent Component counter from the Child Component.
Parent Component (PropsApp.jsx)
import React, { useState } from 'react'
import Child from './Child'
export default function PropsApp(){
const [counter, setCounter] = useState(0)
const updateMyCounter = () => {
setCounter(counter + 1)
}
return(
<>
<hr></hr>
<h1>This is Parent</h1>
<h2>{counter}</h2>
<Child updateParent={updateMyCounter} />
</>
)
}
Child Component (Child.jsx)
export default function Child(props){
return(
<>
<hr></hr>
<h1>This is Child</h1>
<button
onClick={props.updateParent}
>
Update Parent Component
</button>
</>
)
}
Click on the Update Parent Component and see the magic
React.createClass method has been deprecated in the new version of React, you can do it very simply in the following way make one functional component and another class component to maintain state:
Parent:
const ParentComp = () => {
getLanguage = (language) => {
console.log('Language in Parent Component: ', language);
}
<ChildComp onGetLanguage={getLanguage}
};
Child:
class ChildComp extends React.Component {
state = {
selectedLanguage: ''
}
handleLangChange = e => {
const language = e.target.value;
thi.setState({
selectedLanguage = language;
});
this.props.onGetLanguage({language});
}
render() {
const json = require("json!../languages.json");
const jsonArray = json.languages;
const selectedLanguage = this.state;
return (
<div >
<DropdownList ref='dropdown'
data={jsonArray}
value={tselectedLanguage}
caseSensitive={false}
minLength={3}
filter='contains'
onChange={this.handleLangChange} />
</div>
);
}
};
The idea is to send a callback to the child which will be called to give the data back
A complete and minimal example using functions:
App will create a Child which will compute a random number and send it back directly to the parent, which will console.log the result
const Child = ({ handleRandom }) => {
handleRandom(Math.random())
return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>
To pass data from a child component to a Parent component in React:
Pass a function to the child from the parent that receives values.
When the values change in the child component call the function
with the updated values.
e.g.
const Parent = () => {
const handleChange = values => {
alert(JSON.stringify(values) );
//do something with the values
}
return (
<Child handleChange={handleChange} />
);
}
const Child = ({handleChange}) => {
return (
<button onClick={()=> handleChange('values you wish to pass') }}></button>
);
}
NB: As of react 16 I would recommend using functional components in almost all cases.
You can even avoid the function at the parent updating the state directly
In Parent Component:
render(){
return(<Child sendData={ v => this.setState({item: v}) } />);
}
In the Child Component:
demoMethod(){
this.props.sendData(value);
}
Pass data from child to parent Component using Callback
You need to pass from parent to child callback function, and then call it in the child.
Parent Component:-TimeModal
handleTimeValue = (timeValue) => {
this.setState({pouringDiff: timeValue});
}
<TimeSelection
prePourPreHours={prePourPreHours}
setPourTime={this.setPourTime}
isPrePour={isPrePour}
isResident={isResident}
isMilitaryFormatTime={isMilitaryFormatTime}
communityDateTime={moment(communityDT).format("MM/DD/YYYY hh:mm A")}
onSelectPouringTimeDiff={this.handleTimeValue}
/>
Note:- onSelectPouringTimeDiff={this.handleTimeValue}
In the Child Component call props when required
componentDidMount():void{
// Todo use this as per your scenrio
this.props.onSelectPouringTimeDiff(pouringDiff);
}
You are passing a wrong function to child component and your parent class doesn't have handleLanguage function. You can pass like this instead: <SelectLanguage onSelectLanguage={this.handleLanguageChange}/>. I think if a function is absent in a class its would would be None.
your parent component should be like this :
render() {
return (
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
);
}
Best way to pass data from child to parent component
child component
handleLanguageCode=()=>(langValue) {
this.props.sendDatatoParent(langValue)
}
Parent
<Parent sendDatatoParent={ data => this.setState({item: data}) } />;
import { useEffect, useState } from "react";
export default function App() {
const data = (data) => {
console.log("data", data);
};
const myData = {
name: "hi this is my data"
};
return <Form onSubmit={data} myDatasa={myData} />;
}
const Form = (props) => {
console.log("myData", props.myDatasa.name);
const [choreDesc, setChoreDesc] = useState();
const handleSubmit = (e) => {
e.preventDefault();
props.onSubmit(choreDesc);
};
const handlechange = (e) => {
setChoreDesc(e.target.value);
};
return (
<form
onSubmit={(e) => {
handleSubmit(e);
}}
>
<label>Chore description:</label>
<br />
<input
name="choreDesc"
type="text"
value={choreDesc}
onChange={handlechange}
/>
<br />
<input type="submit" value="Add Log" />
</form>
);
};
```
Passing Data between Parent and Child Component in React Hook
Passing the function to child,
and wait child passing back the value by calling parent's function
parent (../app.js)
import MyCOMP from "../component/MyCOMP"; //import child component
export default function MyMainPage() {
return(
<>
<MyCOMP
//pass function to child and wait child passback the changed value
// 1.Click child component passing function to child
ParentFunction={(x)=>{
console.log('Child Pass Back Value',x)
// 3. Parent received data
// after you get the value change you can ultilize another function, useEffect or useState
}}/>
</>
)
}
child (../component/MyCOMP.js)
export default function MyCOMP({ParentFunction}){
return(
<>
<button onClick={()=>{
// 2. Child passing back value to parent
ParentFunction("Child reply ANSWER is ","fm 99.8");}}>Click Me</button>
</>
)
}
Result
after click the button, parent class show "fm 99.8" sting value (the
child's value)
Please comment below, if it help you, or you got another idea