A Brief Introduction to React Components
A component is an isolated piece of the interface. In a typical blog homepage, you might find components like the Sidebar and the Blog Posts List. These components can also be composed of other components. For example, you could have a list of Blog post components, with each component representing a different blog post and having its own unique properties.
React simplifies the process of creating components. In fact, everything in React is a component, even plain HTML tags. These tags are added by default.
The following two lines of code achieve the same thing: rendering <h1>Hello World!</h1>
into an element with the ID app
. The first line uses JSX, while the second line achieves the same result without JSX by using React.createElement
:
`` import React from ‘react’ import ReactDOM from ‘react-dom’
ReactDOM.render(Hello World!, document.getElementById(‘app’))
ReactDOM.render( React.createElement(‘h1’, null, ‘Hello World!’), document.getElementById(‘app’) ) ``
As you can see, React.createElement
is an API provided by React to create components. By changing the first parameter of this method, you can create different tags. The second parameter is an object of props. In this case, we don’t need any props, so we pass null
.
This is how we can use React to work with the built-in HTML components. However, as your application grows, you’re likely to outgrow these built-in components. What React excels at is allowing us to compose a user interface by creating custom components.
Custom Components
There are two ways to define a component in React: function components and class components.
Function Component:
`` const BlogPostExcerpt = () => { return (
Class Component:
`` import React, { Component } from ‘react’
class BlogPostExcerpt extends Component { render() { return (
Until recently, class components were the only way to define a component with its own state and access to lifecycle methods. This allowed you to perform actions when the component was first rendered, updated, or removed.
However, React Hooks have introduced a new way of working with function components, making them more powerful. In the future, we may see fewer class components, although they will still be a valid way to create components.
There is also a third syntax that uses the ES5 syntax without classes:
`` import React from ‘react’
React.createClass({ render() { return (
However, this syntax is rarely used in modern ES6 codebases.