Your first React component

By Bernie FitzGerald •  Updated: 08/21/23 •  6 min read

Let’s start with the definition of a React component.

A reusable, encapsulated piece of the UI that can have its own logic, state, and rendering behavior.

Let’s break that down.

  1. Reusable – once you write your component, you can drop the component anywhere in your application.
  2. Encapsulated – each component is a standalone entity in the system
  3. Logic – using plain JavaScript, each component can perform its logic before rendering
  4. State – each component manages its state. State is just the data related to that component.
  5. Rendering behaviour – this is just how the component will look on the screen

Coding Your First React Component

Now that we understand what a React component is, it still may not be obvious how you should code one. We will now code our first functional React component.

As this is a functional component, we create a plain JavaScript function.

function Article() {
	
}

As you can see, this is just a simple function. Next, we need the function to create some output to render to the screen. This output is the return value of our function.

function Article() {
  return (
    <div>
      <h1>Title</h1>
      <p>Body text</p>
    </div>
  );
}

If we run this code, we’ll see a heading and some text.

At this point, we have a stateless component. One that uses no data to render itself. Let’s change that by updating our articles header text to come from outside of our component.

Adding Props To Your Component

There are many ways that data can come into our component. This example uses the simplest form of props (properties). Props are passed into a component by a parent.

function Article({title}) {
  return (
    <div>
      <h1>{title}</h1>
      <p>Body text</p>
    </div>
  );
}

When the above code is rendered, whatever text is passed as the heading prop will be rendered as the heading. The {title} code is how you inject JavaScript into your HTML in React. Whatever value title currently holds will be substituted into the HTML output.

The code below shows a parent component passing the heading to our article component.

<Article title={"My Title"}/>

We can now add a second prop that contains the body text of the article.

function Article({title, body}) {
  return (
    <div>
      <h1>{title}</h1>
      <p>{body}</p>
    </div>
  );
}

We now have a component whose text is completely driven by the parent component.

<Article title={"My Title"} body={"The body text of the article"} />

Adding State To The Component

State is a little bit more complicated than props. In this example, we’ll use the basic hook useState to store state in the component. Remember, state is just the data that the component controls.

useState is a hook that will return an array of two elements. The first is the current state value and the second is a function you use to update your state. It sounds complicated initially, but it is quite straightforward once you start using it.

In our case, we want to store the language of the article in state. We can then use this value to alter how the text looks.

const [language, setLanguage] = useState('English')

The above functions return the state value language and the function we can use to update that state value setLanguage. It also sets the default language to English.

So if we want to change the language to French, we use the below code:

setLanguage('French')

Let’s add this to our component:

function Article({title, body}) {
  const [language, setLanguage] = useState('English')
  
  return (
    <div>
      <h1>{title}</h1>
      <p>{body}</p>
    </div>
  );
}

Adding Logic To The Component

Now that we have added the state variable language to our component, we can test the incoming text to see what language it is and set the variable appropriately.

As a simple example, we can look for the word Bonjour in the body of the text. If we find this word, we will set the language to French.

To add logic to the component, we are just writing plain JavaScript code in the function. We will put our code after setting up the state variable and before the return statement.

import { useState } from "react";

export default function Article({title, body}) {
    const [language, setLanguage] = useState('English')
    
    if (body.includes("Bonjour")) {
        if (language != "French") {
            setLanguage("French")
        }
    }

    return (
    <div>
      <h1>{title}</h1>
      <p>{body}</p>
    </div>
  );
}


Adding Rendering Behaviour To The Component

Now that we are setting the current language in state, we can use this state to change how the component renders.

The return statement of the component drives the UI. Currently, it outputs the title and body with a h1 and p tag respectively.

Let’s make all French articles use a h2 tag for the header.

To do this, we need to add a condition that tests for the current language and sets the tags appropriately.

We’ll do an inline check of the language state and set the tags accordingly.

Note: this is not necessarily the best way to do this, but it does highlight the conditional output aspect that we’re trying to explain.

With this being said, our return statement now looks like this:

return (
    <div>
      {language == 'English' && <h1>{title}</h1>}
      {language == 'French' && <h2>{title}</h2>}
      <p>{body}</p>
    </div>
  );

As you can see, we can easily change our output based on the component’s state. You can output completely different HTML based on the current state. This is where React components shine.

The realm of possibilities is endless. You can change the text of a button from Sign In to Sign Out based on whether a user is logged in. You could change a menu to display differently on a mobile device compared to a laptop screen.

The Finished Component

The finished component now looks like this:

import { useState } from "react";

function Article({title, body}) {
  const [language, setLanguage] = useState('English')
  
  let french = body.includes("Bonjour");
  if (language == 'English' && french) {
    setLanguage('French')
  }

  return (
    <div>
      {language == 'English' && <h1>{title}</h1>}
      {language == 'French' && <h2>{title}</h2>}
      <p>{body}</p>
    </div>
  );
}

export default Article;

When you look at the component as a whole, you can see how it is encapsulated concerning its logic and HTML output. The component knows how to change based on state, and the component could be dropped into any part of an application.

Bernie FitzGerald

Keep Reading