One shared instance between multiple React components
reactjs - How can we share a state variables between two React components on the same page? - Stack Overflow
how to you share state between sibling components?
The most challenging thing for me about React is sharing state variables between components.
Videos
In this case, if you have given a pascal case naming for the text input such as function TextInput(){...} , then react will consider this as a separate component even if this is defined in the same file. This is why the state variables of the App component are not within the scope of TextInput
You can mitigate this by following either of the following approcahes,
- Make text input a normal function which returns the JSX
function textInput(){
// the state variable 'success' and 'setSuccess' will be normally accessible here
return(
<div>
<input type="text" />
<div>
)
}
//return for the 'App' component
return(
<>
{textInput()}
</>
)
Passing the state as
propsto theTextInputcomponentIf you follow this approach, then you can have the
TextInputcomponent in a separate file as well
//parent 'App' component
function App(){
const [success, setSuccess] = useState(false);
return(
<>
<TextInput success={success} setSuccess={setSuccess}></TextInput>
</>
)
}
function TextInput(props){
const {success, setSuccess} = props;
// In here you can refer success and setSuccess normally as you would even if this is in a separate file
}
To share the state you need to declare the state in the parent component (App in your case) and send it to the child component (TextInput)
e.g.
function App() {
const [success, setSuccess] = useState(false);
...
return (
<TextInput success={success} setSuccess={setSuccess} />
);
}
function TextInput({success, setSuccess}) {
// use success/setSuccess from props
}
I have been pulling my hair why such an easy thing to do in other frameworks like asp, or asp.net (hello session variable),is soooo difficult in react. Ok so how do I share state from one component to another component. I tried callback but no do. Now I am trying context. But is redux is the one that I should use?