#How to export selected value of dropdown to another react file.
1 messages · Page 1 of 1 (latest)
You need to lift up the state or you might want to consider using a state manager to store this value for you
can you plz elaborate more with example? Thank you
Yes of course.
So what lifting a state means. It is very simple, you literally take the state from a component, and move it 1 or more levels higher in your component tree.
We have a component which hold a state:
const ChildComponent = () => {
const [counter, setCounter] = useState(0)
const increment = () => setCounter(prevCounter => prevCounter + 1)
return (
<div>
<h1>{counter}</h1>
<button onClick={increment} type="button">Increment</button>
</div>
)
}
Now we want to be able to use this state somewhere else as well.
The first thing we can do is to lift up the state 1 level higher:
// The state now lives in the ParentComponent,instead of the ChildComponent
const ParentComponent = () => {
const [counter, setCounter] = useState(0)
const decrement = () => setCounter(prevCounter => prevCounter - 1)
return (
<div>
<ChildComponent counter={counter} decrement={decrement} />
</div>
)
}
// ChildComponent become a dummy component
const ChildComponent = ({ counter, decrement }) => (
<div>
<h1>{counter}</h1>
<button onClick={decrement} type="button">Decrement</button>
</div>
)
}
This way we can share the state with multiple components. We could add a SiblingComponent which takes advantage of the state lifting:
// The state now lives in the ParentComponent,instead of the ChildComponent
const ParentComponent = () => {
const [counter, setCounter] = useState(0)
const decrement = () => setCounter(prevCounter => prevCounter - 1)
const increment = () => setCounter(prevCounter => prevCounter + 1)
return (
<div>
<ChildComponent counter={counter} decrement={decrement} />
<SiblingComponent counter={counter} increment={increment} />
</div>
)
}
const ChildComponent = ({ counter, decrement }) => (
<div>
<h1>{counter}</h1>
<button onClick={decrement} type="button">Decrement</button>
</div>
)
}
const SiblingComponent = ({ counter, increment }) => (
<div>
<h1>{counter}</h1>
<button onClick={increment} type="button">Increment</button>
</div>
)
}
Now this could become very messy if you need this state somewhere in your application 4-5 level deep. That's something we call prop drilling. We don't need to be scared of passing props down, 2-4 level in my experience is still acceptable, but it could get very cumbersome after more then 4 levels.
In that case we could take advantage of the react's context api or other state manager libraries. I suggest you to learn the context api first as in most cases it is more than enough even in large scaled applications.
You will probably learn how to use redux, jotai , zustand etc... later on but it is important to know the tools react can provide as sometimes it's better or easier to use it.