How to Make React Component Reusable 

How to Make React Component Reusable?

In this article, I am going to discuss How to Make React Component Reusable with Examples. Please read our previous article where we discussed Dynamic Data and Working with Expressions in JSX.

How to Make Components Reusable in React?

In our previous article, we have passed our data through variables and constants. In this article, we will see how can we make this component reusable. Well, we can already reuse it. In App.js, where we’re using it, we can simply write <ExpenseItem></ExpenseItem> multiple times.

How to Make React Component Reusable with Examples

If we save everything, we got three ExpenseItems.

How to Make React Component Reusable with Examples

So, It is super easy to reuse a component. You can use it as often as you want. But at the moment it’s not really reusable. Yes, it’s technically more than once, but it’s always displaying the same data. And the reason for this is that the data is baked into this component. Now, think about regular JavaScript without React for a second. There, as we mentioned already, we also use functions to split functionality across multiple smaller codebases and also to have reusable functions which we can call multiple times. Now, when we write functions in JavaScript, we make these functions reusable by accepting parameters.

function emailIsValid(email){
      return email && email.includes(‘@’);
}

That allows us to call one of the same functions with different parameter values. And, therefore, the function may produce different results for different input values, but it’s still always the same function being called. And React basically has the same built-in concept. We can make our components reusable by using parameters and a concept called props in React.

Let’s take another example, not the code we’ve been working on. Let’s say in your App component, you have a goalItem variable or constant defined which holds a string ‘Finish!’. And then let’s say you have a custom component, the CourseGoalItem component, which has a list item inside of it where this goalItem should be output.

How to Make React Component Reusable with Examples

We can have a custom component that should output a list item where the goalItem should be output dynamically. The problem is that the goalItem variable lives in the App component, not in the CourseGoalItem component. And to a certain extent, that is good because it makes the CourseGoalItem independent if it doesn’t store the concrete value internally. But, of course, we want to define what’s being output by CourseGoalItem with the help of the variable managed in the App. And we don’t have direct access to the HTML code that is output by some components in other components. We can’t just send our stored data there, but, instead, we can utilize a concept called props.

We can pass data to the custom component by adding an attribute. And inside that component, we can then get access to all these attributes which might have been set on our custom component. Again, we’re basically building our own custom HTML elements. And just as HTML elements can have attributes, it turns out that with React, our own custom components can also have attributes. There, this concept is just called props instead of attributes. And props simply stand for properties. We can set properties of our own custom components.

How does this props concept work though?

In ExpenseItem, we have the date, the title, and the amount, and we’d like to output this but it shouldn’t be stored in here but instead in App.js.

There, in the App component, we could have another constant or variable, expenses, which is an array. So multiple expense items. And every expense here is a simple JavaScript object which has a title like ‘Household Expense’, which also has an amount like the 25000, and where we have a date like the new Date that we created in ExpenseItem before. And we have three such expenses here,

const expenses = [
      {title: ‘Household Expense’, amount: 25000, date: new Date(2023, 4, 27)},
      {title: ‘Travel Expense’, amount: 1300, date: new Date(2023, 4, 27)},
      {title: ‘Education fees’, amount: 5000, date: new Date(2023, 4, 27)}
];

In the expenses array, we have 3 objects. And now we want to pass the data of these different objects to these different ExpenseItems. That means we want to make these ExpenseItems configurable from the outside.

How to Make React Component Reusable with Examples

The data should not be stored inside of them but instead received from outside. And that works with this props concept that we mentioned above.

In App.js, we can simply add attributes to these custom HTML elements, so to these components. For example, we can add a title attribute here to ExpenseItem and set this to a value of ‘Household Expense’. Since we already have the expenses array, we can also dynamically retrieve the title stored in the first ExpenseItem. And we can do this by using the single-curly-brace syntax. We cannot use this between the opening and closing tags of elements. We can also use it for assigning values to attributes. So, we can assign expenseItem’s title as,

<ExpenseItem title={expenses[0].title}></ExpenseItem>

Here, expenses[0] means the first object of the array expenses and the title is the property of the object. The Expenses array contains 3 objects and each object has 3 properties. And now this title is being passed to this ExpenseItem. Now, we can do the same for the amount and date as,

<ExpenseItem
      title={expenses[0].title}
      amount={expenses[0].amount}
      date={expenses[0].date}
></ExpenseItem>

You just have to make sure that the part after the dot matches the property names in the expenses array because we are accessing these objects. Now, we hit the auto-format code (SHIFT + ALT + F) to make this easier to read by splitting these across multiple lines. We can now do the same for the other ExpenseItems as,

<ExpenseItem

        title={expenses[0].title}

        amount={expenses[0].amount}

        date={expenses[0].date}

></ExpenseItem>

<ExpenseItem

        title={expenses[1].title}

        amount={expenses[1].amount}

        date={expenses[1].date}

></ExpenseItem>

<ExpenseItem

        title={expenses[2].title}

        amount={expenses[2].amount}

        date={expenses[2].date}

></ExpenseItem>

Now, if we save that, we see no change, though, because we only did the first half of the work we need to do. We added these attributes with any names of our choice here because these are our custom elements, hence these attribute names are up to us. But inside of that component code, inside of ExpenseItem.js, we also now need to do something with these received attribute values. This’s the other half that is missing.

Now, the question is how do we get access to the values defined in the place where we use our custom components? The answer is parameters. We mentioned that in regular JavaScript, we use parameters for passing data into functions, and it is kind of similar to React. However, we’re now not getting a title, an amount, and a date parameter, as you might think,

function ExpenseItem(title, amount, date) {…} // this is wrong

but, instead, we get one parameter. React will ensure that we get one parameter in every component which we use as a component like we’re doing it here for ExpenseItem. And that one parameter will be an object which holds all the received attributes as properties. Hence the name is props for the overall concept. Therefore, we get one parameter, and you can name this parameter whatever you want.

function ExpenseItem(data) {… } // This is correct way

How to Make React Component Reusable

It’s your function. You can name the parameter as data but, typically, it’s named props to make it clear that this is “this” object which holds all the values we get for the attributes on our custom element. And to be precise, we get key-value pairs in this props object here which is passed in, by React automatically. The keys will be the attribute names defined here, so title, amount, and date in our case. And the values, of course, will be the values that we set in App.js,

How to Make React Component Reusable

So, if we want to output the received title, amount, and date, we can now access props like {data.date},

return (

    <div className=”expense-item”>

      <div className=”expense-item__date”>{data.Date}</div>

      <div className=”expense-item__description”>

        <h2>{data.title}</h2>

        <div className=”expense-item__price”>₹{data.amount}</div>

      </div>

    </div>

  );

getting access to this data parameter and then there to the title property which will exist because we set a title attribute. Now, if you chose a different name than the title here, like, for example, name, then you have to access props.name here. So, the key by which you access your props object has to be the name you picked for your attribute. You have to make sure that the key and attribute names match. Otherwise, it will not work. Now, we can now get rid of the three constants that we created in ExpenseItem.js

How to Make React Component Reusable

since we now get all the data we need from outside the component. So, we’re not defining the data inside of the ExpenseItem component, inside of this function, but, instead, it’s defined in App.js and passed into ExpenseItem for the different usages of ExpenseItem through attributes. And that’s how you share data between React components. You can make your components truly reusable and configurable by using this props concept, which is one of the key concepts React has to offer. You’ll use props all the time, so keep it in mind.

Props are a super important concept because it allows you to make your components reusable, and it allows you to pass data from another component to this component. If you save everything and run the code, you will get,

How to Make React Component Reusable

Here, we can see different expenses are rendered with different titles, different dates, and different amounts. Below is the complete code for ExpenseItem.js and App.js

App.js:
import ExpenseItem from "./components/ExpenseItem";

function App() {
  const expenses = [
    { title: "Household Expense", amount: 25000, date: new Date(2023, 4, 27) },
    { title: "Travel Expense", amount: 1300, date: new Date(2023, 4, 27) },
    { title: "Education fees", amount: 5000, date: new Date(2023, 4, 27) },
  ];

  return (
    <div>
      <h2>Hello Coders!</h2>
      <ExpenseItem
        title={expenses[0].title}
        amount={expenses[0].amount}
        date={expenses[0].date}
      ></ExpenseItem>
      <ExpenseItem
        title={expenses[1].title}
        amount={expenses[1].amount}
        date={expenses[1].date}
      ></ExpenseItem>
      <ExpenseItem
        title={expenses[2].title}
        amount={expenses[2].amount}
        date={expenses[2].date}
      ></ExpenseItem>
    </div>
  );
}

export default App;
ExpenseItem.js:
import "./ExpenseItem.css";

function ExpenseItem(data) {
  return (
    <div className="expense-item">
      <div className="expense-item__date">{data.date.toISOString() }</div>
      <div className="expense-item__description">
        <h2>{data.title}</h2>
        <div className="expense-item__price">₹{data.amount}</div>
      </div>
    </div>
  );
}

export default ExpenseItem;

In the next article, I am going to discuss Adding JavaScript Logic to React Components with Examples. Here, in this article, I try to explain How to Make React Component Reusable with Examples. I hope you enjoy this How to Make React Component Reusable article.

Leave a Reply

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