Component Reusability in React Application

In this tutorial, we will see how we can reuse a Component in React Js application. Reusability is a very important part when it comes to writing clean and effective code for software. Reusability reduces additional code and duplication. Let’s see how we can reuse a Button Component in React.

Component Reusability in React Application



Note: Please go through how to set up React application before continuing this article.

Step 1: Create a Button Component

 function Button(props) {
   return (
   
   )
 }

In the above code, we have created a Button Component which is returning button element with on click event taking increment value as a parameter.

Step 2: Create a Display Component

 function Display(props) {
   return (
   
{props.message}
); }

In the above code, Display Component is used to display the value when we click on Button Component.

Step 3: Create an App Component

 function App() {
   const [count, setCount] = React.useState(0);
   const incrementCount= (incrementValue) => setCount(count + 
   incrementValue);
    return (
     
)};

We have already explained the above code in our previous tutorial where we have learned one-way data flow in React. We will discuss here what additional changes we have added in this.

Previously, Button Component onclickfunction doesn’t have a parameter. But now it takes a parameter. We have made three copies of Button Component and passing different increment values. Each Button Component will increment the current value by 1, 10 and 200 respectively.

If you look closely, you will notice that increment count is a function that is been called by onclickfuntion event of Button Component and eventually it has been passed to the Button Component function (through props) as a parameter to the real DOM button’s onclick event. This is how all React works.

This is how we are reusing Button Component in React by making it parameterized. We will share more knowledge on React in our upcoming React Tutorials.

Admin

Tutorial Funda will keep you updated with the latest Programming Languages, Software Tools and related technologies used in Software Development.

Leave a Reply

Your email address will not be published. Required fields are marked *