#301DaysOfCode – Learning React – Week 2


Components

Components are the bread and butter of React; they are compact and reusable pieces of code that are responsible for one job. Most of the time, components will be used to render HTML.

Creating a Component

To create a component, you’d start out by creating a new variable, React, which is an imported JavaScript object.
The methods you need in order to use React are in this object – it is the React library.

import React from 'react'

You also need to import ReactDOM to help you with interacting with the DOM, and to render your components.

Components must also be derived from a component class, which just allows you to make a bunch of components. The component class is:

React.Component

Creating your own component class involves subclassing the above class, using this syntax:

class ComponentName extends React.Component {}

Class names should be capitalized, and are normally written in UpperCamelCase.

The body must include a render method, that usually returns a JSX expression. This is where you describe how your React component should be built.

render() {
    return <p>Good day!</>;
}

After you’ve done all this to make a component class, you are ready to make a React component, a component instance, which is just:

<MyComponent />

This is a JSX element. The name should match whatever you called your component class. JSX elements are either component instances, or like HTML. The capitalization in the component instance lets you know this is not an HTML tag, that it is in fact a component instance.

When you make a component, the methods of its component class are then inherited by that component, such as render(). You could make any number of these component instances and they would all inherit that same render().

The last thing to do then, is to render the component, which is similar to how we were rendering JSX elements before:

ReactDOM.render(
    <MyComponent />,
    document.getElementById('app')
);

The JSX you created will then be added to the virtual DOM by the value returned from the render() method within the component class. Pretty neat!

Conclusion

This past week was spent learning about components in React, which are really the essence of React. To me they seem pretty intuitive, they act as normal classes would and have inheritance. You can have multiple instances of a component as you could a class/object. You put them inside of <> which also reminds me a lot of the way Angular works. These components then get rendered using the Virtual DOM. I can start to see how stacking up these small pieces add up to a complete site. Next week I hope to get into a little more of the advanced stuff! Stay tuned!