Video Course

Getting Started with React: Lesson 4 of 14

Creating Your First Component

Up Next

Making an Input Component

Autoplaying in 7 seconds!

Cancel

Let's create our first component! It will be called App and comprises out entire application. We will start out by putting it in our app.js file. Add the following above the call to ReactDOM.render.

class App extends React.Component {
  render() {
    return (
      <div className='app'>
        <p>Scotch School rocks!</p>
      </div>
    );
  }
}

We have created our component using the JavaScript class syntax. We extend React's Component base class, which gives up much of the functionality React is famous for. We added a render method to our component. Whatever is returned from this method is what gets put onto the page in our browser. Inside this, we can use any sort of JavaScript magic we want! Above, we are simply outputting a div with a paragraph in it. One thing to note. Notice how there is an attribute on our div called className. This is what we set to add a class attribute to our component. It is className because the class keyword is already used in JavaScript.

Now we need to render this component onto the page. All we need to do is update our ReactDOM.render call.

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

If you look at the browser now and inspect the DOM, you will see that our div and paragraph are both on screen. We can do better though! Our file would get large and unweildy if we had to keep everything in one file. Luckily, we can put a single component in a file and then export that component to then use that elsewhere. Create a file at src/components/App.js, put the App component in it, and then add an export to the bottom.

import React from 'react';

class App extends React.Component {
  render() {
    return (
      <div className='app'>
        <p>Scotch School rocks!</p>
      </div>
    );
  }
}

export default App;

Now we need to remove the App component from our app.js file, and import the App component into it.

import App from './components/App';

View the application in the browser again, and you will see it all looks the same. We didn't break anything. Yay!

Now that we know how to make a component and put it in its own file, we need to start putting our application together. We will start with the zipcode input at the top.

Alex Sears

2 posts

Developing is not only my job but also my passion. I love to teach myself new things as much as I love teaching others. The more people we get involved in this little thing we call "web development," the better we can make it. I mean, we always need more cat videos, right?