0
0
NextJSframework~30 mins

Event handlers in client components in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Event handlers in client components
📖 Scenario: You are building a simple interactive button in a Next.js client component. When the user clicks the button, it should update a message on the page.
🎯 Goal: Create a Next.js client component with a button that changes the displayed message when clicked using event handlers.
📋 What You'll Learn
Use a client component with the directive 'use client'
Create a state variable to hold the message
Add a button with an onClick event handler
Update the message state when the button is clicked
Display the updated message below the button
💡 Why This Matters
🌍 Real World
Interactive buttons with event handlers are common in web apps for user feedback, form submissions, and navigation.
💼 Career
Understanding client components and event handling is essential for building responsive user interfaces in Next.js and React.
Progress0 / 4 steps
1
Set up the client component and initial message state
Create a Next.js client component with the directive 'use client' at the top. Inside the component, create a state variable called message initialized to 'Hello!' using useState.
NextJS
Need a hint?

Remember to add 'use client' at the top and import useState from React.

2
Add a button with an onClick event handler
Inside the MessageButton component, add a <button> element with an onClick attribute. Set the onClick to a function that calls setMessage with the string 'Button clicked!'.
NextJS
Need a hint?

Use an arrow function inside onClick to call setMessage with the new text.

3
Display the message below the button
Modify the returned JSX to include a <p> element below the <button> that displays the current message state.
NextJS
Need a hint?

Use curly braces inside JSX to show the message state.

4
Add accessibility and semantic improvements
Wrap the button and message in a <section> element with an aria-label attribute set to 'Interactive message section' to improve accessibility.
NextJS
Need a hint?

Use a semantic <section> and add aria-label for screen readers.