opencodez

ReactJS Tutorial# 2 – Components and Props

Because you are here, reading this, I assume that you have already created your first React application. It was not hard at all, right? If you havenxt already done so, you will need to check out this article.

Tutorial Index

  1. ReactJS Tutorial# 1 – An Introduction
  2. ReactJS Tutorial# 2 – Components and Props
  3. ReactJS Tutorial# 3 – Component State and Lifecycle
  4. ReactJS Tutorial# 4 – Forms, Events, and Keys
  5. ReactJS Tutorial# 5 x React Flux and Redux
  6. ReactJS Tutorial# 6 – ReactJS Best Practices
  7. 51-important-reactjs-interview-questions

Letxs have a quick look over the project structure.

Like all of us already know, every web application must have HTML file, at least one (in our case it is index.html). We will not go in details what all we have in this file, only mention that somewhere inside the body tag of this file is this line of code.

xdiv id="root"xx/divx

An empty div?

I donxt know if you already start the application, but if you did that, in the browser you should have seen something like the image below. In other cases, you can start the application by running some built-in commands: (make sure you are at the root of the project folder)

npm start

or

yarn start 

But because we have an empty div, shouldnxt we have a white screen? As far as I can see it doesnxt look like that.

Letxs see what we have in the other files, maybe we will find the answer there.

Inside index.js we use ES6 syntax to import several things. One of those imports is ReactDOM from react-dom. This package provides DOM-specific methods that can be used at the top level of your app. In other words this is primary API for rendering into the DOM. Do you remember div with id="root". Well, check the following code.

ReactDOM.render(xApp /x, document.getElementById('root'));

This is the place that render a React component into the DOM in the provided container and return a reference to the component. Do not worry if you have no idea what is component. Just keep reading!

What are the ReactJS Components?

Components are the building blocks of any React app.

They allow you to split the UI into independent and reusable pieces and think about each piece in isolation. A typical React app will have many components.

Open App.js and quickly update the code to something like this.

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render() {
    return (
      xdiv className="App"x
        xheader className="App-header"x
          Hello World
        x/headerx
      x/divx
    );
  }
}

export default App;

Now, go back to the browser and see how your updated component look.
You have just edited your first React component.

Function and Class Components

Letxs now define our first React component. The simplest way for doing that is to write a JavaScript function:

function Welcome() {
  return xh1xHello readerx/h1x;
}

You can write this in the App.js file, just below your imports (it starts on line 4 in our example). Once you are done with that, update App component like this:

...
xheader className="App-header"x
   x Welcome /x
x/headerx
...

Save the changes and go to your browser to see the result.
Congratulations, you have just created your first React component and nested it inside another React component.

Maybe you have noticed that our newly created function (React component) returns a React element. I assume you already know that this React element is JSX and not HTML. In case you did not, check this out.

There is one more way to define a component, by using ES6 class. Classes are in fact xspecial functionsx.

class Welcome extends React.Component {
  render() {
    return xh1xHello readerx/h1x;
  }
}

From Reactxs point of view, the two components above are equivalent.

Props

We already know that to normal HTML elements we can pass attributes like class, href, id, etc. Letxs say we want to show two welcome messages.

...
xheader className="App-header"x
   x Welcome /x
   x Welcome /x
x/headerx
...

If we run the code above it will show Hello reader twice. But what if we want to show Welcome reader and Hello from the other side. Should we create another component for that? Of course not. We just need to use props. In React props is short for properties. It is an object containing a set of values that are passed to React Components on creation using a naming convention similar to HTML-tag attributes. Confusing? Nah.

The main idea is that components can be customized when they are created, with different parameters. These creation parameters are received through props. Same as in HTML, we can pass arguments to React elements. For example, we can pass different messages as arguments to our already created React elements. Something just like this :

...
xheader className="App-header"x
   x Welcome message="Welcome reader"/x
   x Welcome message="Hello from the other side" /x
x/headerx
...

Thatxs it. Now we should see the different messages in our application. Save, Reload and x No. All we can see on the screen is Hello reader, twice.

The things is that we successfully sent our message to Welcome component, but there we didnxt show it. How would we, how would React know what to do with that. Well, it is actually able to take this attribute and gives us acces to them inside our component, by using object we mentioned before. Say its name. Props. You are damn right. Just to be clear, props is not mandatory name, itxs up to you, but you will receive one argument in your function that is passed by default by React and in that object you will find all the properties off the component and properties means the attributes we add to our element just before. In React this is refered like props, thatxs why we will name it props. So after little modification, our React component should look like this.

function Welcome(props) {
  return xh1x{props.message}x/h1x
}

when using class-based components, itxs this.props

class Welcome extends React.Component {
  render() {
    return xh1x{this.props.message}x/h1x;
  }
}

Conclusion

So now we have a reusable component, which has clearly defined a template and inside we use dynamic content which we set from outside, in the place where we actually use that component. Think about all the possibilities that this approach offers. Itxs one big step toward building great and flexible applications.

You can find the sample source code for ReactJS Components and Props at our GitHub repository.

Download Code

x

Tutorial Index

  1. ReactJS Tutorial# 1 – An Introduction
  2. ReactJS Tutorial# 2 – Components and Props
  3. ReactJS Tutorial# 3 – Component State and Lifecycle
  4. ReactJS Tutorial# 4 – Forms, Events, and Keys
  5. ReactJS Tutorial# 5 x React Flux and Redux
  6. ReactJS Tutorial# 6 – ReactJS Best Practices
  7. 51-important-reactjs-interview-questions