How can I extract the useState from the file. It is necessary to export exactly sliderCount for further work. Thanks in advance.
There are 2 files. The first file uses the useState function and changes the state when the button is clicked. In the second file, I want to get the changed state of useState from the first file and continue to work with it.
Make conditions, etc., for example:
if(sliderCount == 1){
console.log('Number 1')
}
if(sliderCount == 2){
console.log('Number 2')
}
First file:
import React, {useState} from "react";
function ContainerAtwSwap() {
const [sliderCount, setSliderCount] = useState(0)
return (
<div className="container_button__swap-main">
<div className="dropdown">
<div className="dropdown-content">
<button className="button__swap-button" onClick={() => setSliderCount(1)}>№1</button>
<button className="button__swap-button" onClick={() => setSliderCount(2)}> №2</button>
<button className="button__swap-button" onClick={() => setSliderCount(3)}>№3</button>
</div>
</div>
</div>
)
}
export default ContainerAtwSwap
Second file:
import React from 'react';
function WorkingEnvironment() {
..here I wanted to make conditions, etc.
return (
<div className='boxControl scroll' id='boxSliderOne'>
<div className='container-slider'>
{}
</div>
</div>
);
}
export default WorkingEnvironment;
CodePudding user response:
One way is to have a parent (of both components) relay the change to the other. Component A will send a changed event to the parent (via a component property event). Then the parent will simply send that changed value to Component B (via a component property).
CodePudding user response:
Grouping your components in one parent component and lifting the state up to their parent is the only way you can share their state. Otherwise you have to implement a redux store or anything like that.
I link you the React doc's below
https://reactjs.org/docs/lifting-state-up.html
CodePudding user response:
That is what the Context API is for: https://reactjs.org/docs/context.html
Of course you could also use Redux, or transfer data from child to parent and to another child, but the Context API solves this in a much easier way and it is built in without any extra dependency.