HackYourFuture React 2 - Week 1 - Exercise 1
This exercise will teach you how to use React Context.
Steps to solve:
- Create a new file and name it
languageContext.js
- Inside the file add the following:
import React, { useState } from "react";
const LanguageContext = React.createContext();
This creates a context for us to use.
- To the same file, add the following component (don't forget to export it!):
export function LanguageProvider({ children }) {
const [language] = useState("dk");
return (
<LanguageContext.Provider
value={{
language: language
}}
>
{children}
</LanguageContext.Provider>
);
}
- In the
App.js
wrap the existing<div>
block withLanguageProvider
so that it looks like this:
export default function App() {
return (
<LanguageProvider>
<div className="App">
<Navbar />
</div>
</LanguageProvider>
);
}
Don't forget to import the LanguageProvider
component first!
- Edit
Navbar.js
and replace:
const [language] = useState("dk");
with:
const { language } = useContext(LanguageContext);
Don't forget to import useContext
and LanguageContext
.