Two panels that must change together share state kept in their parent. Opening one closes the other.
React · beginner · 7 min · 18 steps · free
import { useState } from 'react';
function Panel({ title, isActive, onShow, children }) {
return (
<section>
<h3>{title}</h3>
{isActive ? <p>{children}</p> : <button onClick={onShow}>Show</button>}
</section>
);
}
export default function Accordion() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<div>
<Panel title="About" isActive={activeIndex === 0} onShow={() => setActiveIndex(0)}>
We teach code with pictures.
</Panel>
<Panel title="Contact" isActive={activeIndex === 1} onShow={() => setActiveIndex(1)}>
Write to us any time.
</Panel>
</div>
);
}<Accordion> for the first time: it calls the Accordion function.useState runs for the first time, so React stores the starting value for activeIndex and returns it: 0.Accordion, the parent. Each Panel gets isActive and onShow as props.Panel returns JSX: a description of what the screen should show, <section>…</section>. React has not changed the page yet.Panel returns JSX: a description of what the screen should show, <section>…</section>. React has not changed the page yet.onShow prop, the arrow from Accordion.setActiveIndex(1) does not change activeIndex right away: React queues the update and will render again. In this call activeIndex is still 0.<Accordion> again (render 2): it calls Accordion once more, from the top.useState returns the value React has kept for activeIndex: 1. The starting value is only used on the first render.Accordion returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.Panel returns JSX: a description of what the screen should show, <section>…</section>. React has not changed the page yet.<Panel> again (render 2): it calls Panel once more, from the top. Its props: title = "Contact", isActive = true, onShow = ƒ () => setActiveIndex(1).Panel returns JSX: a description of what the screen should show, <section>…</section>. React has not changed the page yet.Answer: Accordion's. onShow was passed down from Accordion.
Answer: They could not close each other
← Updating Arrays in State · Forms and Controlled Inputs →