DEV Community

Daniel Musembi
Daniel Musembi

Posted on

Understanding React Components

Components in React let you split the page into independent and reusable parts.

Let's visualize this by taking a look at the diagram below.

Image description

Notice that the page can be split into multiple parts.
Each of these "parts" is a component.
The heading is a component, the "new question" button is a component, and the search bar is its component.
This makes organizing the page leaps and bounds easier, but even more importantly, components allow us as developers to separate concerns from one another.

Separation of concerns is a programming principle that states that each concern should be separated into individual pieces.
For example, in the diagram above, the "new question" button (2) should be clicked if a user wanted to add a new question, whereas the search bar (3) would be used if the user wanted to search existing questions.

Functional Components

In React, there are two types of components that you can use: Functional Components and Class Components.

A functional component is a simple JavaScript function.

function Hello() {
  return <h1>Hello world.</h1>
}
Enter fullscreen mode Exit fullscreen mode

The code above defined a functional component called Hello, which returns a simple React element.

Rendering Components

We need to create the corresponding JSX element to display the component.
For example, for our user-defined component Hello:

const el = <Hello />;
Enter fullscreen mode Exit fullscreen mode

Now, we can use our user-defined element and render it on the page:

function Hello() {
  return <h1>Hello world.</h1>
}
const el = <Hello />;
ReactDom.reader(
el,
document.getElementById('root')
);

Enter fullscreen mode Exit fullscreen mode

Remember, all component names need to start with a capital letter.

Class Components

Class components are typically used when there are more advanced user interactions, like forms, and animations.

All class components need to extend the React.Component class.

class Hello extends React.Component {
 render() {
   return <h1>Hello world.</h1>;
}
}

Enter fullscreen mode Exit fullscreen mode

Class components need to have a render method, which is in charge of telling what the page should show.

Top comments (1)

Collapse
 
detzam profile image
webstuff • Edited

Nice 1 minute read