To conduct activities, such as completing a form or opening a new page, buttons are a frequent UI component. You may build reusable button components in Next.js that you can utilize throughout different sections of your application. As a result, maintaining your application will be simpler and your code will be kept DRY (Don't Repeat Yourself).
You must first create a new file in your components folder named Button.jsx
in order to construct a reusable button component. The next step is to define the function "Button," which accepts the parameters text
and onClick.
The text that will be displayed on the button is contained in the text
prop. When the button is clicked, a function specified by the onClick
prop will be called.
Finally, you must return a "button" element that has the text
prop set to the text to be displayed on the button and the onClick
prop set to the handler for the button's onclick event.
Here is an example of a reusable button component in Next.js:
const Button = ({ text, onClick }) => {
return (
<button
type="button"
style={{
margin: 10px,
}}
onClick={onClick}
>
{text}
</button>
);
};
export default Button;
Once you have created your reusable button component, you can import it into any other component that you want to use it in. For example, you could create a component called MyComponent
that uses the Button
component to render a button with the text "Click me!".
Here is an example of how to use the Button
component in another component:
import Button from "../components/Button";
const MyComponent = () => {
return (
<div>
<Button text="Click me!" onClick={() => console.log("Button clicked!")} />
</div>
);
};
export default MyComponent;
This will render a button with the text "Click me!". When the button is clicked, the console.log
function will be called and the message "Button clicked!" will be logged to the console.
You can also use the Button
component to create buttons with different styles. For example, you can add a class to the button element to apply a custom style. For example:
import Button from "../components/Button";
const MyComponent = () => {
return (
<div>
<Button text="Click me!" onClick={() => console.log("Button clicked!")} className="my-custom-class" />
</div>
);
};
export default MyComponent;
This will render a button with the text "Click me!". The button will also have the class my-custom-class
applied to it. You can use this class to style the button in your CSS file.
Top comments (4)
This is definitely not NextJS but rather basic React. NextJS default rendering strategy is SSR, this will not work unless
'use client'
is specified. Please adjust the misleading title to ....in React.Remember that NextJS has pages router and app router. You don't need to use
use client
if you are using the pages router and in this case I used the pages router, so no need for 'use client'.Which version of Next.js are you using?
I used NextJS v13.4 with pages router