The #1 Trick In Learning React That Separates Success From Failure

If I were to ask you what the first real obstacle is for most people in learning React, what do you think it would be?

Some JavaScript concept they don't know well enough?

A coding pattern that's tricky to remember?

No, it's even simpler than that.

It's not something that relates to JavaScript or code in any way.

Yet it's a skill that every React developer needs to know to be able to build applications. And it's one which you'll know by the end of this article.

We're going to dive into what holds people back from getting a true understanding of React. And that happens by not focusing on this one thing first, before jumping into the code.

We're going to start by diving into the core concepts of React. To know the key concepts is crucial to see the takeaway of this particular lesson, so follow through to the end.

If you're brand new to React, there will be some work required to grasp it all. You may need to read this article a couple of times before it all makes sense.

But stick with it—the payoff will be worth it.

So what is this obstacle, exactly?

We'll get to that and much more... but first of all, welcome!

This post is the 2nd in a series designed to get you up and running with React in 2020.

If you're new, take a moment now and sign up for the full series right here.

Not only will doing so help you get the most out of this article, but you'll also get exclusive content to come. Don't miss out on that.

Quick React Recap

In the last lecture we covered some essential topics:

  • Why right now is the best time to learn React as a new or existing developer
  • How the development landscape has changed over time, moving from websites to web apps
  • How the creation of React addressed these new changes in app development

React arrived in 2013 as a better way to build web apps with JavaScript. It's often referred to as a library for building UIs, short for "user interfaces". UIs are the part of the application with which a user interacts in general and aren't limited to the web.

Most any dynamic web application can be remade in React. Many libraries enable us to write React code and run it different environments. For example, React Native allows us to write React apps for mobile and Electron for the desktop.

In other words, React's power lies in allowing us to write our app once and run it wherever we choose.

Building Our First User Interface

And in light of React's versatility, we can recreate any site or user interface that we see on the web.

For this lesson, let's remake part of an app that you likely use every day—Google Search.

https://res.cloudinary.com/codeartistryio/image/upload/v1578576179/01-09-2020/Screen_Shot_2020-01-08_at_5.22.41_AM_rprwyi.png

This may seem ambitious if you are brand new to React, but it requires a knowledge of only two simple concepts:

HTML and basic JavaScript functions.

What's the way we build out a user interface without knowing React or even JavaScript?

Using HTML elements as part of a simple HTML document.

Here's how we would show the first three results that come up when you search for "reactjs" in Google.

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>
  </head>

  <body>
    <section>
      <div>
        <a href="https://reactjs.org"
          >React - A JavaScript Library for Building User Interfaces</a
        >
        <div>
          <h3>reactjs.org</h3>
        </div>
        <div>
          React makes it painless to create interactive UIs.
        </div>
      </div>
      <div>
        <a href="https://en.wikipedia.org/wiki/React_(web_framework)"
          >React (web framework) - Wikipedia</a
        >
        <div>
          <h3>https://en.wikipedia.org › wiki › React_(web_framework)</h3>
        </div>
        <div>
          React is a JavaScript library for building user interfaces.
        </div>
      </div>
      <div>
        <a href="https://twitter.com/reactjs?lang=en"
          >React (@reactjs) | Twitter</a
        >
        <div>
          <h3>https://twitter.com › reactjs</h3>
        </div>
        <div>
          The latest Tweets from React (@reactjs).
        </div>
      </div>
    </section>
  </body>
</html>

Using static HTML alone would be fine if we only needed to show a few links.

But how could we display 100s or 1000s of links this way, all with different data, as a search engine might need to do?

What's a better, that is, a simpler and more extensible way of writing this?

HTML alone is not going to be the answer. We'll need a way of making our site more dynamic to display as many links as we need.

When it comes to adding behavior to a site, we need JavaScript. And since our goal is to build great apps with JavaScript, we know to use React.

Going From HTML to React

Let's turn our static HTML into a dynamic React app.

Sound difficult?

It's simpler than you think.

We can build a React app out of a single HTML document (see the description of a SPA in the previous article for review).

All we have to do to is bring React in with the following external scripts.*

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>

The first is for building our React app, and the second is for displaying, or rendering the React app in the browser.

The first is React, the second ReactDOM.

The third script is to bring in a tool called Babel. We'll touch on what that does in a bit.

Here's what our code looks like at this point:

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
  </head>

  <body>
    <!-- our script must have type="text/babel" for Babel to work -->
    <script type="text/babel">
      // React code will go here
    </script>
  </body>
</html>

... and it's almost a React app.

Note that we have a script where we can write our React code, but no HTML.

Let's fix that.

Creating and Rendering Our React App

Every React app must have what's known as an entry point.

The entry point is an HTML element where we insert our React application into the page.

The conventional entry point is a div with the id of root (<div id="root"></div>)

We'll add that, then use the render() function from ReactDOM to do the work of rendering the app.

The first is the app itself, meaning our HTML from before, and the second must reference our entry point. We can create that reference by saying document.getElementById('root').

So now we have everything we need to run our React app:

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
  </head>

  <body>
    <div id="root">

    </div>
    <!-- our script must have type="text/babel" for Babel to work -->
    <script type="text/babel">
            ReactDOM.render(
      <section>
      <div>
        <a href="https://reactjs.org"
          >React - A JavaScript Library for Building User Interfaces</a
        >
        <div>
          <h3>reactjs.org</h3>
        </div>
        <div>
          React makes it painless to create interactive UIs.
        </div>
      </div>
      <div>
        <a href="https://en.wikipedia.org/wiki/React_(web_framework)">React (web framework) - Wikipedia</a>
        <div>
          <h3>https://en.wikipedia.org › wiki › React_(web_framework)</h3>
        </div>
        <div>
          React is a JavaScript library for building user interfaces.
        </div>
      </div>
      <div>
        <a href="https://twitter.com/reactjs?lang=en">React (@reactjs) | Twitter</a>
        <div>
          <h3>https://twitter.com › reactjs</h3>
        </div>
        <div>
          The latest Tweets from React (@reactjs).
        </div>
      </div>
    </section>, document.getElementById('root'))
    </script>
  </body>
</html>

And if we look at our result, it works like before. Perfect!

Now let's use React to improve our site by dynamically displaying our links.

Making Code Reusable with Components

If we examine our HTML structure, each link consists of the same parts. Each has a url, a title, a shorter url, and an excerpt. For each link, we have to repeat the same HTML elements again and again.

In programming, if you're having to repeat yourself a great deal, it's likely a sign that your code your code can be simplified and shortened, in some way. As programmers, we always strive to repeat ourselves as little as possible.

We try to write code that is DRY, where you "don't repeat yourself."

From the previous article, we saw that React is, at core, JavaScript plus some features to help us build apps.

And since we're working with JavaScript, what is a JavaScript feature that allows us to create or output something as many times as we like?

A function.

So let's create one here, and we'll call it Link.

function Link() {
  // create link HTML output
}

The reason being that we want this function to return or output a link's HTML every time we call it.

To do that, let's return our first link's HTML:

function Link() {
  return (
    <div>
      <a href="https://reactjs.org">
        React - A JavaScript Library for Building User Interfaces
      </a>
      <div>
        <h3>reactjs.org</h3>
      </div>
      <div>React makes it painless to create interactive UIs.</div>
    </div>
  );
}

So now let's use it to display each link it returns.

To do so, instead of calling it like Link(), in React, we can write it like it was an HTML element <Link />.

If you've seen this for the first time it might bend your brain a little bit.

Here we are using HTML syntax, but we are calling a JavaScript function! You'll get comfortable with it as you see this more often.

(Also, did you notice that we didn't have to use an opening and closing tag, like it was a normal HTML element? More about that in a minute.)

But wait, wait a second...

How does React convert this HTML-looking syntax into valid JavaScript?

It does so with the help of a special tool called Babel, the third script we added. You can see how it works in action here:

https://res.cloudinary.com/codeartistryio/image/upload/v1578576193/01-09-2020/Babel_Gif_za8ght.gif

What's happening?

Babel, a JavaScript tool called a compiler, converts ("compiles") this code that looks like HTML into valid JavaScript.

This HTML, which is in fact JavaScript, is called JSX, which stands for "JavaScript XML."

XML, if you're not familiar, is a slightly stricter way of writing HTML.

Stricter means that we need to use a closing forward slash for elements with one tag. For example: <input> in HTML as valid JSX is <input />.

So to reiterate, JSX is not valid JavaScript code.

Meaning, you couldn't put JSX in a browser and expect it to work. We need both a compiler, like Babel to convert it into valid JavaScript, and then React to use that created JavaScript.

So now to use our custom Link element, we remove all three of the links' HTML and replace them with three Links, like so:

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
  </head>

  <body>
    <div id="root"></div>

    <script type="text/babel">
      ReactDOM.render(
        <section>
          <Link />
          <Link />
          <Link />
        </section>,
        document.getElementById("root")
      );
    </script>
  </body>
</html>

And if we look at our result, we do indeed have three links.

This is the power of React: it takes the reusability of JavaScript functions, but allows us to use them like they were HTML.

Crazy, right?

We refer to these custom elements made with JavaScript as components.

So we've gained a great deal of readability here by using components. We don't have any confusion about what we're looking at if we've named our components well. No need to read through a ton of HTML elements to see what the app displays.

We see immediately that we have three custom links.

The Anatomy of a Function Component

Now that we know how components operate, let's take a second look at our Link function component:

Our code may look pretty straightforward, there are a few subtle things you should take note of here:

function Link() {
  return (
    <div>
      <a href="https://reactjs.org">
        React - A JavaScript Library for Building User Interfaces
      </a>
      <div>
        <h3>reactjs.org</h3>
      </div>
      <div>React makes it painless to create interactive UIs.</div>
    </div>
  );
}
  1. The function component name is capitalized: Link instead of link. This is a required naming convention for React components. We use a capitalized name to distinguish components from normal functions. Note that functions which return JSX are not the same as normal JavaScript functions.

  2. Notice how the JSX we are returning has a set of parentheses around it. As you are first writing your React code, it's easy to forget these parentheses, which will result in an error. Wrap your JSX in parentheses if it span mores than one line.

  3. Finally, our Link function returns some JSX. Every React component must return either JSX elements or other React components. And yes, React components can return other components.

So since React components can return other React components, we can make an App component.

This App component will contain our entire set or tree of components and will show of what our app consists.

And with an App component, this makes our render method much easier to read:

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
  </head>

  <body>
    <div id="root"></div>

    <script type="text/babel">
      function Link() {
        return (
          <div>
            <a href="https://reactjs.org">
              React - A JavaScript Library for Building User Interfaces
            </a>
            <div>
              <h3>reactjs.org</h3>
            </div>
            <div>React makes it painless to create interactive UIs.</div>
          </div>
        );
      }

      function App() {
        return (
          <section>
            <Link />
            <Link />
            <Link />
          </section>
        );
      }

      ReactDOM.render(<App />, document.getElementById("root"));
    </script>
  </body>
</html>

We see from this code that React components have a hierarchy or order like HTML elements. As a result, we can refer to different parts of our component tree as either parents or children.

In this case, for example, to each rendered Link component, App is the parent. To App, all three Links are its children.

Note that whenever we render or return JSX, there can only be one parent component. But a parent component can have as many child components (as well as elements) as needed.

When we look at the output of our code, you've likely noticed the following problem—

We have three instances of the same link! That's because we are using the same data for each link we create. Yet we know each link has different data—a different title, url, short url and excerpt.

So how do we pass in unique data to our components?

Passing Unique Data to Components With Props

If we wanted to pass some title text to a normal JavaScript function we would do so like this:

Link("Our link title here");

But how to we do pass data to function components?

Normal HTML elements accept data in the form of attributes. But unlike HTML attributes, attributes aren't recognized on React components. The data doesn't stay on the component itself. Where do they go?

As arguments to the function component.

Again, this is something we're familiar with since we know the basics of functions.

We know that functions output data using return and accept data with arguments.

If we had an HTML element, say a div with an attribute called "title", this code would be invalid. HTML doesn't have a title attributes for any of its elements:

<div title="Our link title here"></div>

But if we created this title "attribute" on our Link component:

<link title="Our link title here" />

This is valid. And since we wrote title like an attribute on our component, it is passed to the Link function as an argument called "title".

In code we can think of it like:

const linkData = { title: "Our link title here" };

Link(linkData);

Notice that the linkData argument is an object.

React collects and organizes the data passed to a given component as a single object.

The name for data passed to a component, such as title, is props.

All prop values exist within the function component itself on a props object.

And since our goal is to use our title prop within our Link component, we can write the following:

function Link(props) {
  return <a>{props.title}</a>;
}

We use this curly braces {} syntax to insert the title prop from props.title wherever we want. And the same applies to any other prop passed down to a component.

These curly braces allow us to insert or interpolate dynamic values wherever we need.

So now we have everything we need to fix our links. For each of the Link components, we need to pass down their title, url, short url, and excerpt as individual props:

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
  </head>

  <body>
    <div id="root"></div>

    <script type="text/babel">
      function Link(props) {
        return (
          <div>
            <a href={props.url}>{props.title}</a>
            <div>
              <h3>{props.shortUrl}</h3>
            </div>
            <div>{props.excerpt}</div>
          </div>
        );
      }

      function App() {
        return (
          <section>
            <Link
              title="React - A JavaScript Library for Building User Interfaces"
              url="https://reactjs.org"
              // props consisting of two or more words must be written in camelcase
              shortUrl="reactjs.org"
              excerpt="React makes it painless to create interactive UIs."
            />
            <Link
              title="React (web framework) - Wikipedia"
              url="https://en.wikipedia.org/wiki/React_(web_framework)"
              shortUrl="en.wikipedia.org › wiki › React_(web_framework)"
              excerpt="React is a JavaScript library for building user interfaces."
            />
            <Link
              title="React (@reactjs) | Twitter"
              url="https://twitter.com/reactjs"
              shortUrl="twitter.com › reactjs"
              excerpt="The latest Tweets from React (@reactjs)."
            />
          </section>
        );
      }

      ReactDOM.render(<App />, document.getElementById("root"));
    </script>
  </body>
</html>

Looking at our output, we still get the same result.

But there was a bit of a trade-off here—

Through props, we were able to make our Link component much more readable.

Now we can make any Link based off of whatever (valid) prop data we give it.

But now you can see that our App component got a lot bigger by providing the prop values immediately on each Link.

Isn't there a way that we can move all this data somewhere else?

Let's do that.

Separating The Data From Our UI

Let's move our data out of the component tree and put it somewhere more convenient, but still use the data as needed.

To do that we'll make an array of objects with the link data to pass down to the Link components through props.

This allows us to put it our data wherever we want, in another JavaScript file even. The benefit is that it doesn't clutter up our components anymore.

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
  </head>

  <body>
    <div id="root"></div>

    <script type="text/babel">
      const linkData = [
        {
          title: "React - A JavaScript Library for Building User Interfaces",
          url: "https://reactjs.org",
          shortUrl: "reactjs.org",
          excerpt: "React makes it painless to create interactive UIs."
        },
        {
          title: "React (web framework) - Wikipedia",
          url: "https://en.wikipedia.org/wiki/React_(web_framework)",
          shortUrl: "en.wikipedia.org › wiki › React_(web_framework)",
          excerpt: "React is a JavaScript library for building user interfaces."
        },
        {
          title: "React (@reactjs) | Twitter",
          url: "https://twitter.com/reactjs",
          shortUrl: "twitter.com › reactjs",
          excerpt: "The latest Tweets from React (@reactjs)."
        }
      ];

      function Link(props) {
        return (
          <div>
            <a href={props.url}>{props.title}</a>
            <div>
              <h3>{props.shortUrl}</h3>
            </div>
            <div>{props.excerpt}</div>
          </div>
        );
      }

      function App() {
        return (
          <section>
            <Link title="" url="" shortUrl="" excerpt="" />
            <Link title="" url="" shortUrl="" excerpt="" />
            <Link title="" url="" shortUrl="" excerpt="" />
          </section>
        );
      }

      ReactDOM.render(<App />, document.getElementById("root"));
    </script>
  </body>
</html>

Now how do we display each Link with it's data using the linkData array?

If you've worked with arrays before, to get each element we loop or iterate over the array. Here, for each loop, we can pass the props data down to the Link component again.

This pattern is a very common one in React. So much so that there is a special array method that we can use to perform this iteration, called .map(). It is not the same as the map method in regular JavaScript—it is for working with JSX and components alone.

<!DOCTYPE html>
<html>
  <head>
    <title>reactjs Search Results</title>

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
  </head>

  <body>
    <div id="root"></div>

    <script type="text/babel">
      const linkData = [
        {
          title: "React - A JavaScript Library for Building User Interfaces",
          url: "https://reactjs.org",
          shortUrl: "reactjs.org",
          excerpt: "React makes it painless to create interactive UIs."
        },
        {
          title: "React (web framework) - Wikipedia",
          url: "https://en.wikipedia.org/wiki/React_(web_framework)",
          shortUrl: "en.wikipedia.org › wiki › React_(web_framework)",
          excerpt: "React is a JavaScript library for building user interfaces."
        },
        {
          title: "React (@reactjs) | Twitter",
          url: "https://twitter.com/reactjs",
          shortUrl: "twitter.com › reactjs",
          excerpt: "The latest Tweets from React (@reactjs)."
        }
      ];

      function Link(props) {
        return (
          <div>
            <a href={props.url}>{props.title}</a>
            <div>
              <h3>{props.shortUrl}</h3>
            </div>
            <div>{props.excerpt}</div>
          </div>
        );
      }

      function App() {
        return (
          <section>
            {linkData.map(function(link) {
              return (
                <Link
                  key={link.url}
                  title={link.title}
                  url={link.url}
                  shortUrl={link.shortUrl}
                  excerpt={link.excerpt}
                />
              );
            })}
          </section>
        );
      }

      ReactDOM.render(<App />, document.getElementById("root"));
    </script>
  </body>
</html>

By moving our data out of the UI and displaying each link using .map(), we have a far simpler React app that can accept as many links as we choose.

Finally, note in our code that where we are mapping over our linkData, the entire expression is surrounded by our curly braces. Be aware that JSX allows us to insert any valid JavaScript expression between curly braces.

How To Build Apps The "React" Way

So if that was all new material to you that might have been overwhelming.

Again, take as much time as you need to grasp the concepts covered. Also, play around with the included code sandboxes to solidify your understanding.

So what was the point of covering these various patterns?

Not only to cover the basics of JSX and how React combines HTML and JavaScript, but also to show you how React developers think.

How do you think like a React developer?

By knowing how to break down our UI into reusable components.

When a React developer plans out an application they want to make, they start by:

  1. Identifying all individual parts of the app, and

  2. Seeing what parts can be made into reusable components. We do that by seeing if each part has the same visual (HTML) structures and accept the same or very similar sets of data (through props).

Now to come full circle, let's take a new look at the starting UI that we wanted to recreate at the beginning. If we were to look at this like a React developer, it might look something like this:

https://res.cloudinary.com/codeartistryio/image/upload/v1578576202/01-09-2020/Components_aepi94.png

As you learn more about React in this series and move onto making your own apps, make sure that you look at the UI you want to make and have an idea of what components they need to be broken into.

The better you get with this skill and make a habit of it when you work with React, the more easily you'll understand how to build your app's features, how each component functions within the app as a whole, and the faster you'll be able to build large-scale applications with ease.

What You Can Do Now

Great work in this lesson and for sticking it out to the end.

We've covered a ton of ground in this lesson:

  • The basics of React elements and components
  • JSX and using function components
  • Passing dynamic data to components through props
  • Inserting data with curly braces {}
  • Displaying multiple components with arrays and .map()
  • Mapping out the reusable parts of our app (components) from the beginning

Now that you've made it this far, keep it going!

Sign up here to stay on track with the rest of the series.

Good work and I'll see you in the next article.

*You can find these scripts here from the official React documentation, reactjs.org.

No Comments Yet