Components are like functions that return HTML elements. Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and returns HTML via a render function. Components come in two types, Class components and Function components, in this tutorial we will concentrate on Class components.
When creating a React component, the component’s name must start with an upper case letter. The component has to include the extends React.Component
statement, this statement creates an inheritance to React.Component, and gives your component access to React.Component’s functions. The component also requires a render()
method, this method returns HTML. A component must be exported.
class Home extends React.Component { render() { return <h2>Hello World!</h2>; } } export default Home;
Here is the same example as above, but created using a Function component instead. A Function component also returns HTML, and behaves pretty much the same way as a Class component, but Class components have some additions, and will be preferred in this tutorial.
function Home() { return <h2>Hello World!</h2>; }
function components are a simpler way to write components that only contain a render
method and don’t have their own state. Instead of defining a class which extends React.Component
, we can write a function that takes props
as input and returns what should be rendered. Function components are less tedious to write than classes, and many components can be expressed this way.
function Home(props) { return <h2>Hello {props.name}!</h2>; }
If there is a
function in your component, this function will be called when the component gets initiated. The constructor function is where you initiate the component’s properties. In React, component properties should be kept in an object called constructor()
state
.
You will learn more about state
later in this tutorial.
The constructor function is also where you honor the inheritance of the parent component by including the super()
statement, which executes the parent component’s constructor function, and your component has access to all the functions of the parent component (React.Component
).
class Home extends React.Component { constructor() { super(); this.state = {name: "Folau"}; } render() { return <h2>Hey this.state.name</h2>; } }
A good rule of thumb is that if a part of your UI is used several times (Button
, Panel
, Avatar
), or is complex enough on its own (App
, FeedStory
, Comment
), it is a good candidate to be extracted to a separate component.
All React components must act like pure functions with respect to their props.