React in 7 Minutes

A No-Nonsense Intro to React.js

Matthew Tyson
Oct 30 · 7 min read
Watch How Fast

React is the foremost front-end development framework for a reason.

It can seem complex at first, but its actually pretty easy to get your head around it. This guide breaks it down for you.

Here are the React Essentials we’re going to cover.

  • Component-Based
  • Data-DOM Binding
  • Component Definition
  • Component Nesting
  • Component Interactions
  • Iterating
  • Event Handling
  • State Updating
  • JSX

Watch how fast we can cover this.

No-Nonsense ahead.

Component-Based

React is a component-based UI framework. The essence of component-based UI is that the view is composed of multiple components representing its parts.

In essence, React maintains a tree of components, and those components then are expressed as what is seen on screen. Something like below:

Let’s look at how this works in code.

This code is live at JSFiddle here.

This is what we are creating (so far):

First Version End Result

Simple: displaying a parent div with a child div inside it.


One-Root Container Element

The first thing to keep in mind is that there is one root element. So, the markup in our HTML page looks like this:

<div id=”container”>
</div>

Now let’s tell React what we want to do with this markup. (Note in the JSFiddle that the React minified distribution has been included.)

class Parent extends React.Component {
render() {
return <div class=”parent”>Parent
<Child></Child>
</div>;
}
}class Child extends React.Component {
render() {
return <div class=”child”>child</div>;
}
}ReactDOM.render(
<Parent />,
document.getElementById(‘container’)
);

Don’t worry, this is actually simple.

First, jump to the last statement, where it makes a call ReactDOM.render(...) This is where React get’s associated with you HTML DOM.

  • The first argument (<Parent/>) says to React “These are the components you will draw”
  • And the second argument document.getElementById('container') says: “And this is where to draw them.”

The <Parent /> element is a JSX element, which is analogous to a custom HTML element.

JSX

Don’t worry too much about JSX up front, it is actually a fairly non-surprising bit of technology. It allows HTML-like markup with JavaScript together. In the end, it is turned into JS code that outputs your components.

In general, you can think of JSX as HTML with JS super powers (or JS with HTML super-powers, if you prefer).


Next, let’s see how the JSX knows what to put into place for the <Parent /> tag.

That work is done directly above in the JS, where we define the Parent component:

class Parent extends React.Component {
render() {
return <div class=”parent”>Parent
<Child></Child>
</div>;
}
}

Again we have a render method. This time, the render method returns a simple div with a class, some text content and another component, called Child.

Component Nesting

The <Child> reference is an example of component nesting.

Just below the Parent component definition, is the Child component, also very simple.

You can see how these components (with a bit of CSS) become the output we see. So far, it just looks like a round-about way of outputting HTML.

But the power of components is they contain more than just the view, as we have seen. They also contain behavior and state.

Data-DOM Binding

What I mean by data-bom binding is that the framework takes responsibility for tying the data in the app to its expression or manifestation in the browser DOM. This is unlike jQuery where much of the framework and developer tiem goes into maintaining this corrospondance.

It turns out, this is a very powerful and productivity increasing idea. It underpins the rapid ascension of React, Vue and Angular.

There are essentially two kinds of data in a React component:

  • Properties (or props)
  • State

Properties

First up: properties.

Props are the data on a component that are set from outside via the element properties (hence the name props). In essence, the markup properties allow for a data communication into the component.

Here’s the updated Fiddle: https://jsfiddle.net/fy0rpvtm/1/.

Result with Data Binding

First, notice that the view template for the parent component has changed, to include a property:

Parent, called {this.props.name}

So we can from the JSX template reference this and refer to the component, just like it were an object — which it is.

this.props refers to the set of properties on the component object. That is part of the component state; its the part that is passed into the component from without.

How do you tell the component what this prop will be?

One way is how it is done here: by setting it explicitly on the component when the component is used:

<Parent name=”John Lennon”/>

I want to really drive home the point here that what we are doing is separating the availability of the state into the component, and the specification of what that state’s content is in the use of that component.

That is to say, the component definition is decoupled cleanly from the specification of its properties.

State

Now, in a similar fashion, the component sports a state member property. This internal state of the component.

State is simply put the variables inside the component, visible only to it. State is not set directly from outside.

Here’s an updated Fiddle using state: https://jsfiddle.net/89k1zcdp/

In our case, we are going to programmatically set the parent state in the constructor:

constructor(props) {
super(props); // Normal JS call to super, req'd for react
this.state = { // Set the state
children: [
{name: “Julien Lennon”},
{name: “Sean Lennon”}
]
}
}

Side-Bar: A constructor is a method on an object that is called when the object is created.

There are other ways to set state. State can be daisy-chained from props so that the prop initializes the state (this is not done directly, however, it is mediated via JS code that ties the two together). Or, state can be set via calls to the backend.

In essence, we take the built-in state member property and give it a “children” property, which we then set directly in JSON. Again, this could come from the backend or user input, anywhere.

Iterating

Now let’s see how we output this in an iterative way:

<ul>
{this.state.children.map(function(child, index){
return <li key={ index }>{child.name}</li>;
})}
</ul>

Using the power of JSX to interleave markup and JS, we take the this.state.children object we initialized earlier, and use the JS .map function to output a list item.

Now we want to use our child component. We can update the Parent view template like so:

return <div class=”parent”>Parent, called {this.props.name}
{this.state.children.map((child, index) => {
return (
<Child name={child.name} />
);
})}

So instead of using the HTML UL and LI elements, we are using the Child component we saw before, and passing into the child the iteration data as props.

So the child component can reflect this props, we add to its view markup:

class Child extends React.Component {
render() {
return <div class=”child”>Child named {this.props.name}</div>;
}
}

New Fiddle: https://jsfiddle.net/89k1zcdp/10/

This gives you the sense of iterating and parent-child communication.

So you’ve seen components, props, state, iteration and communicating from parent to child. These are core elements to building UI with React.

Now, let’s see how we can handle an event and remove a child.

New Fiddle: https://jsfiddle.net/89k1zcdp/12/

Basically, we add a button to the list markup in the parent:

<div>
<Child name={child.name} />
<button onClick={(e) => this.removeChild(index, e)}>Remove</button>
</div>

We’ve added the button element with an onClick handler. When the button is clicked, it’ll execute the JS specified.

We use the fat arrow notation again to ensure this resolves to the component object, and use it to simply reroute the call to this.removeChild() passing in the index of the list element clicked.

In a real app, we’d most likely use a primary key from the data that drives the list. For this intro, we’ll just use the array index (not really safe given that JS doesn’t guarantee the ordering of arrays).

Now let’s see how this event is handled:

removeChild(index){
var array = […this.state.children];
if (index !== -1) {
array.splice(index, 1);
this.setState({children: array});
}
}

The removeChild(index) method is added at the same level as the constructor and render() methods on the component.

“Immutability” of State

The essential thing to realize when you look at this code is this: in ReactJS, the state is not directly modifiable. It is only modifiable via setState(). With that in mind, the removeChild() method becomes pretty self explanatory: copy the array we want off the state, remove the element in question, and then set the new, modified array onto the object state with setState().

And here is the final result:

Final Result

Wrap Up

This is a quick, no-nonsense intro to React fundamentals.

With these techniques, you can begin building a skill-set to construct advanced and well-designed app UI.


JavaScript in Plain English

Learn the web's most important programming language.

Matthew Tyson

Written by

www.darkhorse.tech

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade