Understanding React Functional and Class Based Components

Introduction

React has two components which are functional components and class-based components.

React class-based components are stateful. Their stateful nature allows developers to execute complex code functionalities such as state management. Functional components do not provide many capabilities but despite being stateless they are quite useful. You can however pass props to a function from the parent component. We will however learn how to use the useState() hook in the next article which gives the state illusion in functional components.

Code Syntax

function Display() {

return <h1>Your React Functional Component Here</h1>;

}

Creating a React functional component is a no-brainer.

React Class-Based Components

Class-based components as earlier mentioned are stateful. To write them, you have to use JavaScript classes.

class First extends React.Component {

render() {

return (

<h2>Your very first class based component</h2>;

) }

}

This is the simplest of ways to write a class based component in React and use the component with JSX syntax of <First /> to the React DOM as shown.

ReactDOM.render( <First />, document.getElementById("root") );

Re-using the Component

The beauty of React components is that they can be reused in another component by calling their JSX class.

class First extends React.Component {

render() { return <h2>Your very first class based component</h2>;

}

} export default First

The Second Component

import First from './First';

class Second extends React.Component {

render() {

return (

<h2>Your Second class based component</h2>;

<First />

)}

} export default Second

From the above illustration, you can re-use a prior created component by importing its class.

Conclusion

Now that you are aware of React components, in the next article, we will delve into constructors and props in React class-based components.

Happy Reading!