DEV Community

Josephine Luu
Josephine Luu

Posted on

React Functional Components

As you start out learning React, you may have came across React components and became confused. I hope by reading this, you can gain more clarity. As such, I will break down what a React component is, why it's used, and how it's used with a few examples.

What is a React component?
It's simply building blocks being used to break down and simplify how a website works. For example, in the image below, you can see how the Google page is broken down into several parts like Logo, WordBox, SearchButton, etc.

Image description

Why would anyone want to do that?

By breaking down a website with components, it makes it easier for the coder to identify and update any mistakes made. One of the main benefits in using components, is being able to save time by reusing components. These are just a few reasons to use components, but if you want learn about more then I would suggest clicking here.

Functional Components

Functional components are javascript functions that must start with a capital letter. They usually pass in properties, also known as props. To learn more about props, I would suggest clicking here. A example of how a functional component looks:

function WordBox(){
  return <div>Hi!</div>;
}
Enter fullscreen mode Exit fullscreen mode

Another way functional components are written are like this:

const WordBox = () => <div>Hi!</div>;
Enter fullscreen mode Exit fullscreen mode

There is always some top level component and most often it is a component called App. With any component, it can call other components as well. For example,

function App(){
  return (
     <div>
      <WordBox/>
      <Logo/>
     </div>
   );
}
Enter fullscreen mode Exit fullscreen mode

You can see that it's calling the component WordBox we used in the example above and Logo as a component in the picture shown above.

Rendering Components

In order for the components to show, it needs to be rendered using ReactDOM.render() method. Most often there is a file called index.js where ReactDOM.render() is used, although the file name doesn't have to be called that. The method will pass in the top level component as the first argument, and then pass document.getElementById("root") in the second argument. For example,

ReactDOM.render(<App />, document.getElementById("root"));
Enter fullscreen mode Exit fullscreen mode

You can see here that the component App, the top level component, is being called. With document.getElementById("root"), it is getting the element in the HTML file, that you will need to create, with the ID of root. To learn more about the HTML file, I would suggest clicking here.

I hope this provided clarity for you and good luck coding!

Sources used:

-Picture image
-https://reactjs.org/docs/components-and-props.html
-https://www.geeksforgeeks.org/reactjs-components/

Top comments (0)