useContext
by Matt Tyson
HTML
<div id="root" />
CSS
input {
width: 200px;
border: 1px solid #ccc;
padding: 10px;
font-size: 16px;
}
button {
background-color: #42b983;
color: white;
border: none;
padding: 10px;
cursor: pointer;
margin: 10px;
}
div {
font-size: 20px;
margin-top: 10px;
font-family: Fira Code, Consolas, Source Code Pro, monospace;
}
React
const { createContext, useContext, useState } = React;
const AnimalContext = createContext();
const Speak = () => {
const { animalType } = useContext(AnimalContext);
return (
<div>
{animalType === 'dog' ? 'woof' : 'meow'}
</div>
);
};
const Happy = () => {
const { animalType } = useContext(AnimalContext);
return (
<div>
{animalType === 'dog' ? 'wag tail' : 'purr'}
</div>
);
};
const App = () => {
const [animalType, setAnimalType] = useState('dog');
const toggleAnimalType = () => {
setAnimalType(prevAnimalType => (prevAnimalType === 'dog' ? 'cat' : 'dog'));
};
return (
<div>
<button onClick={toggleAnimalType}>Toggle animal type</button>
<div>{animalType}</div>
<AnimalContext.Provider value={{ animalType }}>
<Speak />
<Happy />
</AnimalContext.Provider>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<App/>
);