Modern React: props for Functional Components

franca

Franca

Posted on January 15, 2021

Modern React: props for Functional Components

Most websites have recurrent design elements. As a developer, it saves you time and effort to build reusable code snippets for these elements. They are called components and React is perfect for creating them.

Note: For this article, I assume that you are familiar with basic React concepts.

Level 1: A reusable component

Imagine your website has cats all over the place.šŸ±šŸ±
Letā€™s build a Cat component:

// Cat.js
const Cat = () => <div className="cat">šŸ±</div>
Enter fullscreen mode Exit fullscreen mode

Note: Inside the div we would write our cat JSX.

Letā€™s look at the code a little closer. Thereā€™s no class, because this is a functional component, a modern way to write React. The function is written as an array function, a longer version would be:

// Cat.js
function Cat() {
  return <div className="cat">šŸ±</div>
}
Enter fullscreen mode Exit fullscreen mode

We can use our component anywhere we want:

// App.js
<Cat />
Enter fullscreen mode Exit fullscreen mode

If we want to change the cat, we only have to change it once in Cat.js and it will be applied everywhere. Thatā€™s the idea of components.

Level 2: An adaptive component

Your Cats are fine. But you dream of a website full of different sorts of cats. A first idea might be to create more cat components:

const Cat = () => ...
const ShorthairCat = () => ...
const BengalCat = () => ...
const PersianCat = () => ...
Enter fullscreen mode Exit fullscreen mode

Since the cats only differ in CSS, thatā€™s a lot of JSX repetition. And whatā€™s about your original Cat component? Change every existing <Cat /> in something more descriptive?

The solution: React properties

As all our cats share the same JSX, we can use our Cat component and modify it a little. It would be convenient to specify which type of cat we want when using it:

// App.js
<Cat type="shorthair" />
<Cat type="persian" />
Enter fullscreen mode Exit fullscreen mode

type is a React property we defined ourselves.
Itā€™s inside the JSX tag as would be an attribute in HTML:

<a href="#">link</a>
Enter fullscreen mode Exit fullscreen mode

The href attribute in a specifies the linkā€™s target.
The JSX property specifies the catā€™s type: I donā€™t just want any cat, I want the shorthair cat.

We added a property, but havenā€™t defined it inside the Cat component yet. As for now, React still doesnā€™t know whatā€™s so special about the persian type cat.

First, we have to add an invitation for properties in our component. Weā€™ll use JS object restructuring here to be able to specify exactly what we can use as an argument.

// Cat.js
const Cat = ({type}) => <div className="cat">šŸ±</div>
Enter fullscreen mode Exit fullscreen mode

We now registered that a cat type can be passed to the component.

If we want to display the shorthair cat, we can pass the property typewith the value shorthair:

// App.js
<Cat type="shorthair" />
Enter fullscreen mode Exit fullscreen mode

We registered typeas a valid property. If we log the type, we get the desired value.

// Cat.js
const Cat = ({type}) => {
  console.log(type); // shorthair
  return <div className="cat">šŸ±</div>
}
Enter fullscreen mode Exit fullscreen mode

Now, the fun begins. We have to add our shorthair catā€™s styling. There are several possibilities to do this ā€“ a simple solution is to add a modifier class to be able to define the shorthair catā€™s styling in our CSS file. In the end, our HTML result loos like this:

<!-- In the browser -->
<div class="cat cat--shorthair">šŸ±</div>
Enter fullscreen mode Exit fullscreen mode

Every cat has the class cat, but if a type is added we want this type to be an additional modifier class.
To be able to do this, we need to prepare the class to change according to the passed type. With JS template literals, we can add variables to strings. With the ternary operator, we can provide the fallback if no type gets passed.

// Cat.js
const Cat = ({type}) => {
  return (
    <div className={`cat ${type ? `cat--${type}` : ""}`}>
      šŸ±
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Note: I recommend the React classnames package which makes dynamic classes much more readable.

If we want to pass multiple properties, we can do this as follows:

// App.js
<Cat type="shorthair" name="Leo" />
Enter fullscreen mode Exit fullscreen mode
// Cat.js
const Cat = ({type, name}) => {
  return (
    <div className={`cat ${type ? `cat--${type}` : ""}`}>
      Cat {name} šŸ±
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Now itā€™s your time to try it out. Iā€™ve built a CodeSandbox for you to fork šŸ‘‡


Linklist

React-specific

Modern JS

šŸ’– šŸ’Ŗ šŸ™… šŸš©
franca
Franca

Posted on January 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related