The Components are very import in React because they allow to divide the UI in small, reusable and independent pieces of code, help us to manage easily a project.
In React there are two types of Components: Function Components and Class Components.
In this post, using the project created in “React – How to create a project”, we will see how the Components work and how to use them to create an application.
JSX
Before we start to talk about Components, I want to explain in few words what JSX is.
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods and it converts HTML tags into react elements.
We are not obliged to use JSX but, I advice to use it because it is very powerful and easy to use.
For example, if we need to display a <H1> html tag in a React component, we should write a code like that:
import React from 'react'
const Welcome = () =>
{
return React.createElement('div',null, React.createElement('h1', null, 'Ok'));
}
export default Welcome;
Instead, using JSX, this will be the code:
import React from 'react'
const Welcome = () =>
{
return(
<h1>Ok</h1>
);
}
export default Welcome;
For all information about JSX, go to: JSX – In Depth
FUNCTION COMPONENT
A Function Component is a Javascript function which returns a React element.
We open Visual Studio Code and we create a file called Component1:
[COMPONENT1.JS]
import React from 'react'
const TestComponent1 = ()=>{
return(
<h2><b>Hello World</b></h2>
);
}
export default TestComponent1;
then, we open the file App.js and we add the new component:
import React from 'react';
import './App.css';
import Component1 from './Component1';
function App() {
return (
<div className="App">
<Component1></Component1>
</div>
);
}
export default App;
Now, we save the files and run the application using the command npm start:
CLASS COMPONENT
A Class component is a ES6 Class (Javascript Class), that it is used to render a React element.
It is very similar to a Function Component and in fact they are equivalent from React’s point of view.
The essential different is that a Class Component includes properties and functionalities not present in a Function component like constructor, life-cycle methods and state management.
We open Visual Studio Code and we create a file called Component2:
[COMPONENT2.JS]
import React from 'react'
class User extends React.Component {
render() {
return <h3>Hi, I am a simple User</h3>;
}
}
export default User;
then, in order to display the new component, we have to modify the file App.js:
import React from 'react';
import './App.css';
import Component1 from './Component1';
import Component2 from './Component2';
function App() {
return (
<div className="App">
<Component1/>
<br></br>
<Component2/>
</div>
);
}
export default App;
Now, we save the files and run the application: