Creating your first React component
In a recent post we learnt how to get started with react and setting up webpack and react modules. If you already understand how the setup process works continue reading, otherwise check this post: Quick guide to starting with React js using ES6
Here is the code on our main react file, where we will call our first component.
Now lets create a new folder Component
and than create FirstComponent.jsx
inside it. I am building it using .jsx
file syntax, if you are using .js
go ahead and use it, things will work the same way.
In this file we will first import React and Component from react to use it for creating our first react component.
import React, {Component} from 'react';
With react and component ready for use, now go ahead and create a simple ES6 class as follows:
class FirstComponent {}
At the moment this is an ES6 class but not a react component, so lets extend it to make it a react component:
class FirstComponent extends Component {}
Now we have a react component but it is of no use. React components has a function called render()
which generates the view of our page. Anything that is returned inside the render function is generated into the DOM of the page. Lets go ahead and create one h1
element that our component will render:
class FirstComponent extends Component { render() { return ( <h1>I am the First Component</h1> ); }}
We are almost done, but still we need to export this class. Exporting will help us use this component anywhere in our application. So the final code looks like this:
Now lets use this component in our main.jsx
, just import it from the path and use it as you would use a HTML tag (don’t forget to close it with / ).
Run webpack
and refresh your browser to see your new component in action.
You can also use components inside components in a similar way. Now go ahead and create a few more components and use them inside each other.