React Pass State Across Parallel Components
I have two Components of the same level (no owner-ownee relation). Suppose by clicking "C" in Component A, I set the temperature unit to "C", and clicking "F", I set the unit to "F". In Component B, I need to display the temperature, so I need to get the unit. But that information is in A. I wonder how I can access the state in Component A?
Follow up:
In another Component C, which is also parallel to A and B, I have a link to another page:
<div className="bottom_link">
<Link to={'weather-stations/eaB1rJytnpS5mZ2m'}>view detail</Link>
</div>
I also need to pass the unit info to that page. I wonder what is the recommended way to do this? Thanks.
Answer
The best way to do this now is with the useContext hook. Create a new file that can be called TemperatureContext.js. In there you will need the following:
import {createContext} from 'react'
export const Temperature = createContext(null);
//you can replace null with an initial condition
Then, in your app.js file import the file you made and create a useState value. Then, wrap both Component A and Component B in a provider tag:
import React, {useState} from 'react'
import{Temperature} from '.TemperatureContext.js'
function App(){
const [temperature, setTemperature] = useState();
return(
<Temperature.Provider value={{temperature, setTemperature}}>
<ComponentA>
<ComponentB
</Temperature.Provider>
)}
Then, in each of your components, you can import the temperature state by
import React, {useContext} from 'react';
import{Temperature} from '.TemperatureContext.js';
function ComponentA(){
const [temperature, setTemperature] = useContext(Temperature);
const tempChange(entry)=>{
...
setTemperature(entry)
}
return(
...
)
}
Now, by using the tempChange function in ComponentA, it will alter the state in everything that is wrapped within the Provider tags. Thankfully, react has advanced a long way since this question was posted.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM