0
0
NextJSframework~30 mins

Error.tsx for route errors in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Create an Error.tsx Component for Route Errors in Next.js
📖 Scenario: You are building a Next.js app that needs a friendly error page for route errors like 404 or 500.This page should show a clear message and a button to go back home.
🎯 Goal: Build an Error.tsx component that displays the error statusCode and a message. Include a button that navigates back to the homepage.
📋 What You'll Learn
Create a functional React component named Error in Error.tsx.
Accept a prop called statusCode of type number.
Display the statusCode and a friendly error message.
Add a button that uses Next.js useRouter to navigate back to the homepage when clicked.
Use semantic HTML and accessible attributes.
💡 Why This Matters
🌍 Real World
Error pages improve user experience by clearly showing when something goes wrong and guiding users back to safety.
💼 Career
Creating accessible and user-friendly error components is a common task for frontend developers working with Next.js or React.
Progress0 / 4 steps
1
Setup the Error component with props
Create a functional React component called Error in Error.tsx. It should accept a prop named statusCode of type number. Export this component as default.
NextJS
Need a hint?

Define an interface ErrorProps with statusCode as a number. Then create a function Error that takes { statusCode } as props and export it.

2
Add basic error message display
Inside the Error component, return a main element containing an h1 that shows Error {statusCode} and a p with the text Sorry, something went wrong.
NextJS
Need a hint?

Use JSX to return a main element with an h1 showing the error code and a p with the message.

3
Import useRouter and add navigation button
Import useRouter from next/router. Inside the Error component, call const router = useRouter(). Add a button with aria-label="Go back to homepage" that calls router.push('/') when clicked.
NextJS
Need a hint?

Import useRouter from next/router. Use it to navigate home when the button is clicked.

4
Add semantic and accessible structure
Wrap the content inside a section with role="alert" for accessibility. Add a footer with a small text Contact support if the problem persists.
NextJS
Need a hint?

Use a section with role="alert" to wrap the error message and button. Add a footer with a small support message below.