Journey, React

Day 3: Let’s get to know these Components.

One of the main reasons behind what made React so different is the use of components. So let’s try to understand

  • What they are
  • How to use them

What are components?

Let’s try to wrap our heads around what a component is. The best way I can describe them is like a lego piece. They are small, they can be reused, and they are good for one thing at a time. The thing Components usually do is to render the HTML, because their job is to render information it only makes sense that they need to have a render() function in them. Well this makes total sense to me now. I won’t forget this ever again. 

Because a component  will render information it makes sense that the information will contain HTML, CSS, and some Javascript.

How to use a component.

First things first the name of the component should be the same name of our file, it makes it easier to find our components later.

Let’s create a component called helloworld2 and we will expand on our hello world app from yesterday.

Our final code looks like this:

 

Screen Shot 2018-05-14 at 3.45.23 PM.png

Let’s take a look at the code that changes which is the component itself.

class HelloWorld2 extends React.Component {
   render() {
      return
<h1>Hello, my name is Claudia</h1>
}
}

The component is written as an ES6 class  and we use “extends React.Component which is ES6 way of  extending the Component class.

Next we have our render function which is mandatory because that is what the component is meant to do.

Functions are meant to return something so in this case we are returning our code that we want to display on the screen.

Now how do we get the information on the screen well if you remember from yesterday we have to use our React.DOM.render() function, to which we pass what we want to render and where.

This time we pass in the component as our what and the same div as the where.

var mountComponent = document.querySelector(‘#app’); ReactDOM.render(<HelloWorld2 />, mountComponent);

That’s all there is to components, just remember that they are small chunks of code, like a function. They are reusable and they need to have a render function in them.

Tomorrow we will dive a bit deeper into components.

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s