React JS Components

React JS Components:-

Components let you split the UI into independent and reusable pieces of code. Components help to render your UI, rather describes what should exactly appear on the screen. Lets write a simple react component and see how it works?

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

functionWelcome(props){

return<h1>Hello,{props.name}</h1>;

}

functionApp(){

return(

<div>

<Welcome name="Welcome"/>

<Welcome name="Frugalis"/>

<Welcome name="Minds"/>

</div>

);

}

ReactDOM.render(

<App/>,

document.getElementById('root')

);

This is a basic way of writing components, there is an advanced and good way of writing react components as well. We will see that later.Now lets’ see what happens here.

There is a component created named as Welcome

There is another component named as,App inside this Welcome is called multiple times.

React calls the componentWelcome from the componentApp with as{name: 'Welcome'} the props.

The above code looks good, but this is not good practice generally followed in applications. Let’s write a cleaner code using ES6.

Project Structure:-

Let’s Write Our WelcomeComponent, create a file named Welcome.jsx.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

import React from'react';

classWelcome extendsReact.Component{

constructor(props){

super(props);

}

render(){

return<div>{this.props.name}</div>;

}

}

export defaultWelcome;

Now,React.Component is an abstract base class present in React and must define at least render() method, Constructor and export as module

Let’s write another component App.jsx, create a file named App.jsx:-

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import React from'react';

import Welcome from'./Welcome.jsx'

classApp extendsReact.Component{

constructor(props){

super(props);

}

render(){

return<div>

<Welcome name="Welcome"/>

<Welcome name="Frugalis"/>

<Welcome name="Minds"/>

</div>

}

}

export defaultApp;

Here we are calling our Welcome component multiple times, in react we are allowed to have only one parent tag and multiple child elements can reside inside this.Now we are going to wire up all our components.

Create a file named main.js:-

JavaScript

1

2

3

4

5

import React from'react';

import ReactDOM from'react-dom';

import App from'./App.jsx';

ReactDOM.render(<App/>,document.getElementById('root'));

So we wired up our App component to render in our browser, you can see the difference between writing code in a conventional way and using ES6 way.

How do you decide what components to be created for your UI?

A simple thumb rule is that if your part of UI is used several times make it a reusable component. If there are complex UI sections then also we can break our UI into components.