Listing 17-13: Consuming a Context
Your preferred temperature unit: c
import { useContext } from "react";
import { UnitsContext } from "./contexts/UnitsContext";
const UserPrefs = (props) => {
const unitPrefs = useContext(UnitsContext);
const changeLengthUnit = () => {
unitPrefs.setLengthUnit(unitPrefs.lengthUnit === "cm" ? "inch" : "cm");
};
const changeTempUnit = () => {
unitPrefs.setTempUnit(unitPrefs.tempUnit === "c" ? "f" : "c");
};
return (
<>
Your preferred length unit: {unitPrefs.lengthUnit}
<button onClick={changeLengthUnit}>
Switch to {unitPrefs.lengthUnit === "cm" ? "inch" : "cm"}
</button>
<br />
Your preferred temperature unit: {unitPrefs.tempUnit}
<button onClick={changeTempUnit}>
Switch to {unitPrefs.tempUnit === "c" ? "f" : "c"}
</button>
</>
);
};
export default UserPrefs;
import { UnitsProvider } from './contexts/UnitsContext';
import Header from './Header';
const App = (props) => {
return (
<>
<UnitsProvider>
<Header />
</UnitsProvider>
</>
)
}
export default App;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.