React from Scratch

Nicolas Marcora
7 min readJul 14, 2018

React is a JavaScript library for creating user interfaces. Its core principles are declarative code, efficiency, and flexibility. Simply specify what your component looks like and React will keep it up-to-date when the underlying data changes.

- Official React Documentation

Building applications with JavaScript alone can work, but it quickly becomes unmanageable as your application grows.

Let’s say you’re building a todo app. Wouldn’t it be great if you could just have a simple JavaScript array with strings in it, you defined what a single todo item should look like, and all the todos appeared on the screen?

And what if adding a new todo on the screen was just a matter of adding a string to that JavaScript array? What if removing or editing a todo was also just as simple as removing or editing that item in the array?

This is the power of React. You define things once, you work with your data, and everything else just falls into place without you having to worry about it. Oh, and it’s fast!

Who’s this for?

This article assumes zero knowledge of React. It is meant to be a starting point for beginners, and you will probably also find it helpful if you’re not a beginner, but you feel you’ve moved too fast while you were learning React the first time, and find some of the core concepts a little unclear.

Pre-requisite knowledge

  • Basic HTML
  • Basic JavaScript
  • ES6 (classes and arrow functions)

Following along

I highly recommend you follow along using this StackBlitz template:

https://stackblitz.com/edit/react-from-scratch

StackBlitz is an online editor for web applications powered by Visual Studio Code that will help you get started and following along in seconds.

All I’ve done in this template is import React and ReactDOM, which we’ll need to get started, and I added a little sprinkle of css to make things less boring.

Creating a root div

This will be React’s way into the page, and it is the only html we will actually need to write on our page, because the rest of the html will be injected by React into this div. You can find this div in the index.html file.

Starting with the simplest component (Stateless functional component)

Yes, yes. I know stateless functional component sounds a little scary, but it’s actually just a function that returns a React element. Look at it, isn’t it harmless?

Wait a minute… what’s that HTML doing in JavaScript land?

No, it’s not a typo. And it’s not actually HTML either. This is called JSX and, although it may look like HTML, behind the scenes it is being transformed into JavaScript for us. This allows us to work with a familiar syntax, while retaining all of the power of the JavaScript language. You can find out more about JSX here.

Rendering a component into our root div

This is where ReactDOM comes in handy.
ReactDOM has a render method that takes 2 arguments:

  • What to render (React component)
  • Where to render it (DOM element)

Note: Once our component has been defined, we render it by calling it like we would any other HTML/JSX tag. i.e. App = <App /> (case sensitive).

Styling

Just like with regular HTML, we can give our React elements attributes. For example, you easily target your elements with CSS by giving them a class or an id attribute.

Note: Since the class keyword is already taken in JavaScript, className is used instead.

Also note: Attributes in React are camelCased. For example, if you want to give your element a click event, you need to type onClick instead of onclick.

Interpolation

Since we’re not actually using HTML, but JSX, we have the power to use JavaScript directly inside our components. All you have to do is wrap your JavaScript code with curly braces{}.

Here are just a few examples of what this allows you to do:

Props

Every React component gets passed a props object when rendered. This is how a parent component can send all kinds of things to their children components, like functions, strings, objects, you name it!

Note: Since props are received from above, they don’t belong to the component receiving the props, and you should avoid mutating this data.

Composing components

You can render React components within other React components.

Class components

Sometimes just having props and rendering elements is not enough.
What if you want a component to have some information and methods of its own? Or what if you need something to happen every time a component is updated, or whenever the component is rendered for the first time?

React allows us to do all of those things! But, before we can get started, we will need to transform our humble functional component into a class component.

Here’s how you do it:

Notice how this class extends from React’s base Component class. At the very least, we need to give our class component a render() method, where we define what the component should render, exactly like we did in our stateless functional component, but a tad more verbose.

As it is, this newly transformed component does exactly the same thing as its functional counterpart, but it is now ready to take in some extra logic, as you will see below.

State

What do you do when having data passed down by a parent component is not enough, and you need a component to have some data of its own? React allows your class components to hold their own data in an object called state.

Note: The naming of the state variable is not arbitrary, React knows about this variable, and it won’t work if you call it anything else.

Here’s how you can give a component an initial state:

Modifying state

We said before that props don't belong to a component, so we should avoid modifying them. But state totally belongs to a component, so it's perfectly ok to change it! However, you should never change it directly. Instead, React gives you a handy method called setState to do this very thing.

Note: If you mutate the state object directly, the state will change, but React won’t rerender the app, which will lead so undesired behaviour.

setState takes an object as its first argument. This object should include any keys that you wish to modify. For example, in the example above, our state already has a name key, so to change it, we do:

this.setState({name: 'newName!'})

Any keys that were not already in the component’s state, will be created, and any keys that were not passed in the setState object will not be modified.

Events

Do you want to trigger an action when a button is pressed, or when a form is submitted? Just like in regular HTML, you can add events to your React elements. This allows you to “react” to things like a button click or a form submission (pun totally intended).

Some of the most popular events are: onSubmit, onClick and onChange. The list is longer, and you can learn more about what events are available here.

Remember attributes are camelCased. So use onClick, onSubmit, etc.

Project: Counter

This is it. The moment of truth! Believe it or not, you now have enough knowledge to build your very first React application, so let’s get to it!
Let’s keep it simple and build a counter app for our first example, to help you put everything you’ve just learned to the test.

Your component will need to:

  • Keep track of a counter number.
  • Display that number on the screen.
  • Have and call a method to increase the counter.
  • Have and call another method to decrease the counter.
  • Call these methods from your page. Maybe with buttons?

WARNING: Below this text is the solution to the project. I suggest you stop here, give it a go for yourself, and come back once you’re done to check how I’ve done it and compare.

Counter app in action

So? How did it go? I hope you’ve managed to get your component working! If not, don’t worry, I’m sure you got close. You can take a look at my code below to see how I did it.

Did you enjoy this article? Think I can make it better? Give it a clap (or 50 🙃) or drop me a comment below!

If people find these ramblings useful, I will probably turn this into a series!

Next: In the next article, I’ll show you how to work with different files and how you can extract the - and + buttons into a single, reusable <Button/> component. You’ll see a link to it here when it’s ready!

More where this came from

This story is published in Noteworthy, where thousands come every day to learn about the people & ideas shaping the products we love.

Follow our publication to see more product & design stories featured by the Journal team.

--

--