Components is the basic building blocks of React UI. Every React project consist of different type of components which can communicate each other, manage its own state and they are reusable.
There two types components, functional components and class components. We are focusing on the first in this post.
A functional component is a JavaScript functions which return some web element such as <Div> or it can be any HTML element. Lets create our first functional component
Create a React project from scratch and locate the App.js file under src folder and delete everything within <div className = “App” > If you don’t know how to start a React Project here is the Guide for you.
Create functional component
Create new folder named components under src folder and create a file called Message.js with following content. (You can do this easily with VS Code and ES7 React extension by using rfce command)
import React from 'react'
....
function Message() {
return (<div>
<h1 > Hellow < /h1>
</div>)
}
The component simply return a Hello message. In App.js which is the main component , we can use inside the App Div as
import Message from './components/Message'
.....
....
function App() {
return (
< div className = "App" >
<Message >
</div>
);
Run the project using npm start
Props or properties
What about passing some values to the component which make it more dynamic. With the help props we can pass some values to the component like
<Message/>
<Message person='Chris'/>
We have to modify the component as
import React from 'react'
....
function Message(props) {
return (<div>
<h1 > Hellow {props.person} < /h1>
</div>)
}
Child components
May be you already noticed that component inside <Message> <p>This is a functional component </p> </Message> didn’t show up yet. For this we have specify the props children ( variable always specified inside the { } , curly braces in React. ).
import React from 'react'
....
function Message(props) {
return (<div>
<h1 > Hellow {props.person} < /h1>
{props.children}
</div>)
}
Now you know how to create a functional component in React. It can be a piece of input box with awesome styles or it can be simple box, it us up to you , the developer