I have a main page component in react whose render function looks like this
const MainPage = () => {
return (
<>
<Component1 />
<Component2 />
</>
)
}
And Component has some inputs
const Component1 = () => {
const [val1, setVal1] = React.useState("");
const [val2, setVal2] = React.useState("");
return (
<>
<input type="text" value={val1} onChange={setVal1} />
<input type="text" value={val2} onChange={setVal2} />
</>
)
}
My question is how to get values val1 and val2 in the MainPage component? Thanks in advance
use Redux or Context API in your React Project. Btw you can call the function to get the children component variables value.
Example React using Class
class Parent extends Component {
constructor() {
this.state = {
value: ''
};
}
//...
handleChangeValue = e => this.setState({value: e.target.value});
//...
render() {
return (
<Child
value={this.state.value}
onChangeValue={this.handleChangeValue}
/>
);
}
}
class Child extends Component {
//...
render() {
return (
<input
type="text"
value={this.props.value}
onChange={this.props.onChangeValue}
/>
);
}
}
You can't.
React is based on Unidirectional Data Flow
So to solve your problem you must define an event that will be called from the children.
const MainPage = () => {
const [val1, setVal1] = React.useState("");
const [val2, setVal2] = React.useState("");
return (
<>
<Component1 val1={val1} onChange1={setVal1} val2={val2} onChange2={setVal2} />
<Component2 />
</>
)
}
And Component1
const Component1 = ({val1, onChange1, val2, onChange2}) => {
return (
<>
<input type="text" value={val1} onChange={onChange1} />
<input type="text" value={val2} onChange={onChange2} />
/>
</>
)
}