Skip to content

React Components

sergio edited this page Jan 15, 2021 · 2 revisions

Step 1: write the components

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Let's imagine we want to post a blog article that also display comments made by readers.

class Article extends React.Component {
  render() {
    return (
      <div>
        Dear Reader: Bjarne Stroustrup has the perfect lecture oration.
      </div>
    )
  }
}

a new class, Article, is declared the class extends React's component class (which provides us with built in methods and attributes). the class contains a render() method that defines exactly what the component should render to the page.

class Comment extends React.Component {
  render() {
    return (
      <div>
        Naturally, I agree with this article.
      </div>
    )
  }
}

While the code inside the return() statement looks like simple HTML, it's actually JSX: a specialized JavaScript syntax that resembles regular HTML.

Once we have our components in hand, it's time to actually use them.


Step 2: use the components

Now that we have these components written, all we need to do is make sure some other component is making use of them in its render method. Every React application has some top level component. Very often, this top level component is simply called App.

class App extends React.Component {
  render() {
    return (
      <div>
        <Article />
        <Comment />
      </div>
    )
  }
}

Here we can see JSX coming into play a bit more. The code inside the return() still looks a lot like regular HTML, but in addition to rendering a regular old HTML div element we're also rendering our two components. We've created code that is not only well structured and modular, but also a straightforward description of what we want the App component to do: render the article first, followed by the comment. Here is what the resulting HTML will look like:

<div>
  <div>Dear Reader: Bjarne Stroustrup has the perfect lecture oration.</div>
  <div>Naturally, I agree with this article.</div>
</div>

This unpacks logically. The App component (being our top level component) wraps around both Article and Comment. As you may expect, we refer to the App component as the parent component of both the Comment and Article components. Inversely, we refer to Comment and Article as children components of App.

Clone this wiki locally