so in our project the data will be entered on the 1st page component and we want that data on the 5th page not on the 2nd 3rd 4th page. we are not able to maintain the state of object till the 5th page
Asked
Active
Viewed 75 times
1 Answers
1
You can use a Context item.
You can create an object which can be accesible in multiple components. This can, of course, be combined with state.
1-Create the context (in this case I made a component wrapper to make it easier to include in the code.
export const DataContext= React.createContext({
data: 60, //Default values in case no value is provided
setData: () => {}
});
export function DataContextContainer({children}) {
const [data, setData] = useState(60);
return (
<DataContext.Provider value={{ data, setData}}>
{children}
</DataContext.Provider>
);
}
2-Wrap your desired components (which will read that data) with the component
import {DataContextContainer} from "./DataContextContainer";
...
<DataContextContainer>
...
<YourComponent/>
...
</DataContextContainer>
3- Now you can easily have access to that object in any of the components wrapped using the hook useContext or a context consumer.
import {DataContext} from './DataContext'
...
const {data, setData} = useContext(DataContext);
...
4- Use it in your input:
<input type="text" value={data} onChange={(e) => setData(e.target.value)}/>

Mario
- 133
- 1
- 6
-
what will be the syntax for taking values in input text box – amit chavan Mar 31 '22 at 05:40
-
I dont exactly understand what you mean but I suppose you can do onChange={(e) => setData(e.target.value)} – Mario Mar 31 '22 at 06:41
-
I have created a UseContext component and made a variable inside it. Now i want to take input from input text box and set the value in that UseContext variable . Im not able to understand it – amit chavan Mar 31 '22 at 21:07
-
I updated the answer I gave to add what you should do in your input – Mario Apr 01 '22 at 06:43