I want to practice my react skills and get familiar with compound components and the new APIs within functional components. For an exercise I have created an typical FAQ section. I want the user to be able to expand only one answer at a time by clicking on a question.
In this example I dont know how to identify each question/answer to trigger the toggle without to provide an key or name on each component.
<FaqPanel>
<Faq>
<Faq.Question>Question 1</Faq.Question>
<Faq.Answer>Answer 1</Faq.Answer>
</Faq>
<Faq>
<Faq.Question>Question 2</Faq.Question>
<Faq.Answer>Answer 2</Faq.Answer>
</Faq>
<Faq>
<Faq.Question>Question 3</Faq.Question>
<Faq.Answer>Answer 3</Faq.Answer>
</Faq>
</FaqPanel>
import React, { useState, createContext, useContext } from "react";
import styled from "styled-components";
const Qs = styled.p`
width: 100%;
border: solid 2px;
`;
const As = styled.p`
display: ${props => (props.visible ? "grid" : "block")};
`;
const FaqContext = createContext();
const FaqPanel = props => {
const { children } = props;
const [activeQuestion, changeQuestion] = useState();
const providerValues = { activeQuestion, changeQuestion };
return (
<FaqContext.Provider value={providerValues}>
<div>{children}</div>
</FaqContext.Provider>
);
};
const Faq = props => {
const { children } = props;
return <div>{children}</div>;
};
const Question = props => {
const faqContext = useContext(FaqContext);
function handleClick() {
faqContext.changeQuestion();
}
return <Qs onClick={handleClick()}>{props.children}</Qs>;
};
const Answer = props => {
const faqContext = useContext(FaqContext);
return <As visible={faqContext.activeQuestion}>{props.children}</As>;
};
Faq.Question = Question;
Faq.Answer = Answer;
export { FaqPanel, Faq };
No responses yet.