As we have already seen in the React Basics, components are small chunk of code like functions. They are reusable and helps to manage the UI easily.
We saw earlier in this Components and Props in React post that you can declare the components in two different ways.
When your app is small and it doesn’t require updating the UI, you’d want to go with a function component but as it grows bigger and require some UI modification, you’d want to go for a class component.
I am not saying that you can’t update the UI with a function component but with a function component, you need to render the element again and again to update the UI, which is not the way React suggests to update the UI. React suggests using states to update the UI and with a class component you can do that.
Let’s take a look at the function component first.
function Clock(props) {
return (
Hello, world!
It is {props.date.toLocaleTimeString()}.
);
}
Let’s convert the above function component into a class component.
Step 1: Create an ES6 class.
You can use the same name for the class since in actual app/program, you might have used at multiple places. The class will extend React.Component to have all component’s properties and methods.
class Clock extends React.Component {
...
}
Step 2: Add a single method render() and keep it empty.
class Clock extends React.Component {
render(){
...
}
}
Step 3: Move the same body code inside the render() method.
class Clock extends React.Component {
render(){
return (
Hello, world!
It is {props.date.toLocaleTimeString()}.
);
}
}
Step 4: Replace the props with this.props.
class Clock extends React.Component {
render(){
return (
Hello, world!
It is {this.props.date.toLocaleTimeString()}.
);
}
}
That’s it. The Clock component is a class component now rather than a function component.
class components examples functions