How To Use State In Your Component#
Store Questions And Answers In The State#
To manipulate the FAQ, we will move all the data to the state of the component.
The state of the component is the local state of that specific component.
When the state changes, the component re-renders itself.
We can initialize the state in our functional component body using the useState
hook.
1import { useState } from "react";
2import "./App.css";
3import FaqItem from "./components/FaqItem";
4
5function App() {
6 const [faqList, setFaqList] = useState([
7 {
8 question: "What does the Plone Foundation do?",
9 answer: "The mission of the Plone Foundation is to protect and...",
10 },
11 {
12 question: "Why does Plone need a Foundation?",
13 answer: "Plone has reached critical mass, with enterprise...",
14 },
15 ]);
16
17 return (
18 <ul>
19 {faqList.map((item, index) => (
20 <FaqItem key={index} question={item.question} answer={item.answer} />
21 ))}
22 </ul>
23 );
24}
25
26export default App;
Exercise#
To save space in the view, we want to show and hide the answer when you click on the question.
Add a state variable to the FaqItem
component, which keeps the state of the answer being shown or not, and adjust the render method to show or hide the answer.