I'm building a react website and i'm stuck on a problem that has to do with passing data from a component, back to the App.js file.
so: In my app.js file, i have a Router, that routes any request to path '/signin' to the Component. What i want to do, is i want to take a boolean from the component and store it in the app.js script, so that whenever that boolean is changed in the Component, it also changes on the app.js script.
Any suggestions on how i can do this? Any help at all would be appreciated!
CodePudding user response:
the changeValue function will change the value in the App component. Since value is passed as props to ChildComponent, as soon as it changes, it will change in ChildComponent as well
const App = () => {
const [value, setValue] = useState('')
const changeValue = (value) => {
setValue(value)
}
return (
<div>
<ChildComponent
changeValue={changeValue}
value={value}
/>
</div>
)
}
const ChildComponent = ({changeValue, value}) => {
return (
<div>
<p>{value}</p>
<input
type='text'
onChange={(e) => changeValue(e.target.value)}
/>
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
CodePudding user response:
Store the state at the parent level, and pass down the modifier function to the child via props or context.