Published on

React Components and Props Explained!

We all know what React.js is right? But you know know what React components are? What about props? If not, keep reading in order to learn about React components and React props!🚀

Overview of React components and Props

Figure 1: Overview of React components and Props

React Components Overview

React components are basically objects that allow developers to split the traditional user interface into multiple, independent, reusable modules.

React components are divided into two types: class and function components.

Class components are the classic way of using components in React and they consist of extending the React.Component class. Although class based components are the norm during the early years of React, they are now being replaced by the newer functional component.

Here is a simple example of a class component in React:

class HomePage extends React.Component {

    render() {

        return (
            <div className="col-md-6 col-md-offset-3">
                <h1>Hi {user.firstName}!</h1>
                <p>You're logged in with React!!</p>

                <p>
                    <Link to="/login">Logout</Link>
                </p>
            </div>
        );
    }
}

Functional components are the new way of using components in React. They are basically functions that return JSX.

JSX stands for JavaScript XML and is React's unique syntax extension based on JavaScript and is generally considered as faster, safer and easier than JavaScript. This is due to a variety of reasons including that we can write HTML and JavaScript in it, its ability to convert HTML tags into React elements, and it's reliance on ES6 which is then converted into regular JavaScript at runtime.

Note that functional components are essentially stateless components, meaning they do not adhere to the React component lifecycle. Therefore, it is not possible to define constructors in functional components.

Here is a simple example of a functional component in React:

const Tweet = ({
    data: {
        title,
        body,
        author: { firstName, lastName },
        published,
    },
}) => (
    <Card style={{ margin: '30px auto', width: '400px' }}>
        <CardHeader>{title}</CardHeader>
        <CardBody>
            {body || <p style={{ opacity: 0.5 }}>This tweet has no body...</p>}
        </CardBody>
        <CardFooter>{`${firstName} ${lastName} - published: ${published}`}</CardFooter>
    </Card>
)

export default Tweet;

...
...
...

<div>
    <Tweet data={tweet} key={id} />
</div>

React components have a number of advantages over traditional HTML markup, some of these reasons include:

  • Easier to scale: Let's assume we need to include one hundred <a> tags, each with a different id onto an HTML page. Using static HTML would entail having to create each one of those <a> tags manually, a very time consuming process. If we choose to use React components we can easily render not just <a> tags but an entire component that can act as an <a> tag, using the JavaScript map() method like so:
<table>
    <thead>
        <tr>Link Tags<tr>
    </thead>
    <tbody>
        { arrayContainingOneHundredObjects.map(() => <tr><LinkComponent /><tr>) }
    </tbody>
</table>
  • Easier to update: Let's say you need to make a change in a <li> tag that is present in multiple sections of the webpage. If you're using static HTML you will have to manually find and update every single <li> that is present in the page. If you're using React on the other hand, assuming the <li> tag is contained within a component, you just need to change that single <li> tag and the other instances of that component will be automatically updated throughout the webpage
  • Allows for state management: React components allow for state management with its use of state and props(more on this below). This allows React components to automatically render its elements every time there is a state change, without any explicit action needed by the user. Plain HTML and JavaScript in comparison do not even have a concept of state management, much less implementation. React is the clear winner here.

Now let's move onto React props!🚀

React Props Overview

Props are really a short form notation for properties and they are mainly used to transfer data between React components. A common use of props is to pass data from a parent component to a child component using props.

An important point to mention is that React encourages allowing the passing of data from parent to child components only and not the other way around. Although there are ways to pass data from child to parent components(Here is a link to a Stack Overflow post showing how to do this), this is not looked at as a best practice and should generally be avoided when possible. This practice is looked down upon because of the React's philosophical principle of unidirectional data flow.

Now you might be asking yourself the reason to limit data unidirectional, that is from parent to child component only. Well there are several good reasons for this principle such as being able to improve performance, an easier time debugging applications and having more control over the data. To elaborate on that last point, having more control over the data means that because the data flows only in a single direction, the data flow is much more predictable. This is great for the maintainability of the application as new developers will be able to understand the application much faster and easier down the line. Additionally, having unidirectional data flow creates a single source of truth, meaning that all data relevant to the application is aggregated in a single location(Here is a great article going in-depth about single source of truth)

Now let's go over a simple example of React props in action:


const Parent = () => {
   const [user, setUser] = React.useState({ name: 'Felix' });
   const handleInput = (e) => {
      e.preventDefault();
      setUser({
         ...user,
         name: e.target.value,
      });
   };

   return (
      <>
         <h1>Parent</h1>
         <br/>
         <input onChange={handleInput} value={user.name} />
         <Child user={user} />
      </>
   );
}

const Child = ({ user }) => (
   <>
      <h2>Child</h2>
      <h1>{user.name}</h1>
   </>
);


ReactDOM.render(<Parent />,document.getElementById("app"));

First, we define the Parent component. Inside it, the Child component is called and passed the props user. Then, the Child component can access the user object's properties such as user.name. A every useful attribute of props is that whenever the Parent component's state variables change the updated values for user.name is passed to the Child component almost instantaneously. Here is a gif of this example:

React props in action!🚀

Figure 2: React props in action!🚀

React Components and Props Best Practices

Now as with most software concepts there are some best practices when using components and props that you should know. Some of them include:

Destructuring props: This feature, originally introduced in JavaScript ES6, gives us the ability to extract multiple properties from objects and assign them to unique variables, all done in very few lines of code! Here is a before and after example of a component implementing destructed props:

Before:

const NotDestructuring = (props) => {
  return (
    <div auth={props.auth} key={props.placements.id}>
      <Link
        auth={props.auth.token}
        to={`/attractions/${props.placements.website_url}`}
        key={props.placements.id}
      >
        <img
          alt={props.placements.company_name}
          src={props.placements.company_logo_url}
        />
        <h1>{props.placements.company_name}</h1>
      </Link>
      <CompanyRankings rating={props.placements.company_ranking} />
    </div>
  );
};

After:

const Destructuring = () => {
  const {
    auth,
    auth: { token },
    placements: {
      id,
      company_name,
      website_url,
      company_logo_url,
      company_ranking
    }
  } = this.props;
  return (
    <div auth={auth} key={id}>
      <Link token={token} to={`/placements/${website_url}`} key={id}>
        <img alt={company_name} src={company_logo_url} />
        <h1>{company_name}</h1>
      </Link>
      <CompanyRankings ranking={company_ranking} />
    </div>
  );
};

As you see in the example above, destructuring allows us to eliminate the use of the word props altogether. This has the benefit of making the code much easier to read and allows for greater adherence to the DRY principle by eliminating repeated lines of code. Finally, the number of steps required to access certain object properties are also reduced.

Limit the number of props passed to components: Although props are a very helpful feature in React too much for a good thing is often bad, as is the case here. If lots of props are passed to a single component, it make that component hard to read and maintain down the line. Therefore, try to limit the number of props passed into components down to a reasonable number(no more that 5 is my personal rule). If you truly do need more props passed in, consider breaking down that component into smaller components and dividing the props between the two components accordingly.

Keep components small and specific: This is an important aspect of designing components in React because small, specific components are easier to maintain and understand than large components that encompassing lots of core functionality. Think about it from a debugging perspective as well, would you than debug a large component with lots of tangled logic and code or a small and easy to read component that makes its purpose clear after 10 seconds of reading its code? The latter option is clearly the superior one. So always remember to keep your components small and specific!

Conclusion

Although there are many more details about React components and props that weren't covered in this post, for the sake of brevity Iet us end it here. Hopefully you now have a better idea of what React components and props are, along with why and how we use them.

Thanks for reading this blog post on React Components and Props!

If you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on Twitter and GitHub, connect with me on LinkedIn and subscribe to my YouTube channel.