In the Quiz
component, you currently show the quiz's title and description. You'd like to add a start button that takes the user to the first quiz question. If you wanted a link, you could just use the Link
component and set the to
prop:
<Link to="/quiz/state-capitals/question/vermont">Start</Link>
The slugs are hardcoded in this URL. You can write the path more generally by going into JavaScript mode with backticks and then embedding expressions in a string template:
<Link to={`/quiz/${quiz.slug}/question/${quiz.questions[0].slug}`}>Start</Link>
While links are great, you really want a button:
export function Quiz(props) {
// ...
return (
<div className="quiz-page">
{/* ... */}
<button>Start</button>
</div>
);
}
Both links and buttons beg to be clicked, but unlike a link, a button doesn't know what to do when a click happens. You must tell it. In this case, you need to add an event listener that changes the path using some functions that React Router provides. You will grab a navigate
object, which is an interface to the history of the browser's most recently visited URLs, and manually navigate to your new path:
// ...
import {useParams, useNavigate} from 'react-router-dom';
export function Quiz(props) {
// ...
const navigate = useNavigate();
return (
<div className="quiz-page">
{/* ... */}
<button
onClick={() => {
navigate(`/quiz/${quiz.slug}/question/${quiz.questions[0].slug}`);
}}
>Start</button>
</div>
);
}
Try clicking on the start button. The path change will cause the app to re-render and a new route will match. Click the browser's back button, and you will return through the navigation history to the quiz page.
Now that the user can start up a quiz, you are ready to add inputs to the Question
component so that the user can respond.