What to learn React? Let’s start with the basics. So… Welcome to … yet another React article?!

No, no…the internet is full of react articles, most of them, teaching you how to install its dependencies and start coding right away. This article will be different, bear with me on this 😉

How React Works

Let’s start off with concepts.

The first thing to know about react is that it is actually NOT composed by those tags you see around…that, is the syntax used to make our lives easier when coding with react.

Conceptually, React is a library that allows you to “manually” create components based in Classes and their instances to bind them with data and events.

Well, if you wanted to create a component with React, this is the “original” way to go:

“`js

React.createElement(

  type,

  [props],

  […children]

);

“`

Let’s say you want to add a div to your HTML page with the text “Hello World” in it.

Well, you can simply do that with raw JavaScript (Vanilla JS) with a few lines:

“`html

<div id=”root”></div>

<script>

    const rootElement = document.getElementById(‘root’);

    const divElement = document.createElement(‘div’);

    divElement.textContent = ‘Hello World’;

    rootElement.append(divElement);

  </script>

“`

But if you want to do that exactly same thing using the React lib, you can do so with this:

“`html

  <div id=”root”></div>

  <script src=”https://unpkg.com/[email protected]/umd/react.production.min.js”></script>

  <script src=”https://unpkg.com/[email protected]/umd/react-dom.production.min.js”></script>

  <script>

    const divElement = React.createElement(‘div’, { }, ‘Hello World’);

    ReactDOM.render(divElement, document.getElementById(‘root’));

  </script>

“`

Two ways of doing “the same” thing…or so it appears…

https://blog.vanhack.com/blog/why-learning-code-should-be-your-career-resolution/

React tools

Nowadays we count on tools available to build stuff on top of our code. Those tools are actually layers that will turn our source code into something else. With these tools, we can for example fix lint problems, detect security vulnerabilities, optimize or uglify the resulting code, add a source map to them, or even add a sugar syntaxe layer that will actually interpret our original source code and _transpile_ it into something else. That “something else” is actually **JavaScript**. Yup, the final result is always our beloved triad composed by JavaScript, CSS and HTML.

These are the tools that allow us to add a new pattern that will be transpiled to the final result. In case of react, they ended up with a syntaxe that is very familiar to us, web developers, an HTML based syntaxe.

Now, you can write your components like this:

“`jsx

<Element myProp={someValue}>

    <span>some children</span>

</Element>

“`

In the end, what your transpiler will do is actually port that to a list of calls of JavaScript methods USING the React library, also binding the `someValue` to events.

But how is that binding done? With a State Machine.

https://blog.vanhack.com/blog/5-steps-to-an-international-career-if-you-are-a-developer-with-no-experience/

React functions

React uses the concept of state changing events. Its internal features will observe changes to a given object (the state) and, as they are triggered, it knows where those properties are being used and will then update them and their values.

Also, to optimize it a little further, React will avoid re-rendering your component in case the final result of it is the same, unchanged.

In other words, React will run your functions/listeners, get the result and apply the changes to the state variables. Then it will try and render your component **in memory** in something called _virtual DOM_. And only then, and only IF, the resulting output has changed, it will trigger the rerender of the actual DOM of the page.

Now, why is that?

It turns out that re-rendering DOM elements in your page is very “expensive”, requiring memory, graphics and processing cycles for the browser to do it properly. In memory, though, it’s way cheaper. Other React competitors use different approaches to optimize their rendering process, but still, the ideal is to always only touch the DOM in the parts that are really needed, only when it’s really necessary.

Well, let’s make it work with the syntax we mentioned the easiest way.

We will import _babel_, a transpiler that will be able to deal with our code in real time in the client side. This is not the best approach for production, but is easier to implement and start coding when you’re learning 🙂

“`html

  <div id=”root”></div>

  <script src=”https://unpkg.com/[email protected]/umd/react.production.min.js”></script>

  <script src=”https://unpkg.com/[email protected]/umd/react-dom.production.min.js”></script>

  <script src=”https://unpkg.com/@babel/standalone”></script>

  <script type=”text/babel”>    

    const divElement = <div>Hello World</div>;

    ReactDOM.render(divElement, document.getElementById(‘root’));

  </script>

“`

Working with React attributes

You will realize the code written in the script tag is not a valid JavaScript code…but once we added the `type` to it, the browser will NOT process it as it was JavaScript, it will just “be there”. Babel is the one who is going to get that tag’s content and will process it, then turning it into plain regular JavaScript and append it to the `head` element of your page, therefore, processing the resulting JavaScript.

Awesome, now that we’re all setup, we can go ahead and understand some of the basics I see a lot of people hitting their heads on. And more importantly, understand why they are like that.

First of all…it’s time we talk about attributes.

As you now know, the JSX syntax is basically an easier way to write a set of JavaScript calls. With that in mind, you should understand that the attributes you are passing to your React components are actually NOT html attributes, but JavaScript params.

I know, right?!

Well…now you must remember that HTML is NOT case sensitive. That means `<div someData>` is the same as `<div somedata>` and for that matter, the same as `<dIV sOmEdAtA>`.

React will leverage this to know when you are probably trying to use a variable from your JavaScript scope or actually trying to add an HTML attribute to your element.

For example:

“`jsx

<div

  data-something=”1″

  anotherThing={1}

/>

“`

In this case, your final DOM element will have the `data-something=”1″` attribute in it, which is fine and what we wanted. But it will also have an `anotherthing=”1″` attribute, which we did NOT want.

React knows that we “probably” didn’t want that will will show us a warning message (yes, a warning that is actually an error in the console)

Also, that’s why we can’t use some attributes in react…because they are actually JavaScript words. For example, the `for` attribute in a `label` element.

“`html

<input id=”my-ipt” />

<label for=”my-ipt”>My Input</label>

“`

In React, you will have to use the `htmlFor`:

“`jsx

<input id=”my-ipt” />

<label htmlFor=”my-ipt”>My Input</label>

“`

The same goes for `class`, which you will need to use the `className` instead.

“`jsx

<div className=”my-awesome-css-class” />

“`

Working with Classes

Now…do you remember I mentioned React works on Classes and their instances? What is the “formal” way of naming classes? With the first letter in Upper case.

React will take that in “mind”, and that’s why:

“`jsx

<div>content</div>

// IS NOT the same as

<Div>content</Div>

“`

For React, anything with a first letter in uppercase will be treated as an element that must be rendered/instanced. It will then look for your `Div` element, not the browser’s one.

Did you recognize the message? `Div` is a variable/class/function that is not defined. That’s our plain JavaScript working.

Well, with this, I think you have quite some interesting thoughts and concepts to to put to rest in your mind. 

Creating variables 

Now that you are in the same page with the concepts mentioned in the first part of this article, let’s move on.

When we create a component in React, we can simply create a variable in JavaScript that will hold a construction function…or a class.

This constructor will receive the component’s properties as params:

“`jsx

function MyComponent (props) {

  return (

    <div className=”my-css-class”>

      {props.children}

    </div>

  );

}

“`

Now, other components can use it like this:

“`jsx

<MyComponent>

  The content

</MyComponent>

“`

And the DOM attribute will end with something like this:

“`html

<div class=”my-css-class”>

  The content

</div>

“`

You can relate to that too, to think about how we can add logic to our rendering components.

Everything between `{ }` will be treated by react as variables…not, actually, as JavaScript statements.

For example, you could have something like this:

“`jsx

  <div>

    {props.someVal.toUpperCase()}

  </div>

“`

> Please notice that in this case, you are **counting** on receiving a `someVal` from props and also, that this will be a String…you should **not** simply trust the data you receive, but should validate everything prior to using them.

Procedures

With that in mind, you can now execute procedures within those statements, including ternary conditions or maps.

“`jsx

  <div>

    {someBoolean === true ? “Ok” : “Not”}

  </div>

“`

In the end, every time your component renders, it will resolve to “Ok” or “Not” as the children/content of that div, based on `someBoolean`.

You can also use the return of functions:

“`jsx

function getSomeValue () {
  return 123;
}

  return <div>

    {getSomeValue()}

  </div>;

“`

But remember that functions in JavaScript can both be called or be passed as reference.

And here we find another point where people who are starting with React usually face some hard times.

For example:

“`jsx

function myClickListener () {
  return 123;
}

  return <div onClick={myClickListener}>

    Click me

  </div>;

“`

In this case, we are passing the function `myClickListener` down to the component’s `onClick` param. That function will be executed once the click event is triggered.

But…

“`jsx

function myClickListener () {
  return 123;
}

  return <div onClick={myClickListener()}>

    Click me

  </div>;

“`

Will not. Why?

Well…because while `myClickListener` is the reference to the function that WILL be called in the future…`myClickListener()` is the call of that function, which will be actually replaced by its return, 123. In the end, your component now is `<div onClick={123}>`, and `123` is not a function to be called when the click event is called.

And what about loops?

Well, you can’t have loops within these statements…but as you can have function calls, you can make use of the `Array.map` method.

You see, if you pass an Array to react, it will try and use its `toString` result, so, an array like `[1, 2, 3, 4]` will be rendered as `1,2,3,4` (the same as `[1, 2, 3, 4].toString()`. This, by itself, may be what you need in some cases.

But the Array.map will **return** a new Array containing the return of a function called for each item in the list.

“`jsx

const arr = [ “a”, “b”, “c” ];

  return <div>

    {arr.map(item => item.toUpperCase())}

  </div>;

“`

This will result in `<div>ABC</div>`.

There is one important point to make here, though.

Imagine you have a list of items that you want to use as child components:

“`jsx

function MyComponent (props) {

  const fruits = [

    { id: ‘1’, value: ‘Apple’ },

    { id: ‘2’, value: ‘Banana’ },

    { id: ‘3’, value: ‘Grapes’ }

  ];

  return <ul>

    {

      arr.map(item =>{

        return <li>

          { item.value }

        </li>;

      })

    }

  </ul>;

}

“`

The output will be something like:

“`html

<ul>

  <li>Apple</li>

  <li>Banana</li>

  <li>Grapes</li>

</ul>

“`

Solving issues

That looks fine…until you see the warning message in your browser’s console.

Ah, classic.

That happens because in case something changes in your component and React has to re-render it…how is it supposed to know which line of the array changed?

Remember it compares the output to know what changed? What if the value of the item with the id 2 is now also “Apple”? How should react update the DOM elements? Should the second element’s innerHTML change to “Apple” or should the second element be removed and actually a new first element be added with the content “Apple”?

To solve that, you can add the `key` prop to items in your Array, like so:

“`jsx

 return <ul>

    {

      arr.map(item =>{

        return <li key={item.key}>

          { item.value }

        </li>;

      })

    }

  </ul>;

“`

Now, `key` will be used by React (and will NOT be rendered into your DOM element) to know each line.

When the user changes the second element’s value to “Apple”, its key will still be `2`. React now knows exactly what changed.

Also…that’s why you should NOT use `i`, the loop increment counter, as the key of your items…any change to the array and the `i` will always be `i`.

Let’s say, the user added an `{ id: 4, value: “Pineapple” }` to the top of the list.

When React re-render the list, your `i` would be 0 at this point and therefore, `Apple` will be replaced in the DOM output by `Pineapple`. Then, Banana will be replaced by Apple. Now Grape will be replaced by Banana, and a new line with Grape will be added at the end. The visual result will look the same, but that’s not what you wanted, right?

If your key is the `item.id`, then React will notice that it should only add a line to the top of the list and that’s all, no more changes shall be made to the DOM.

I hope you have found this article useful and fun.

 

See how VanHack
can connect you to top-notch tech talent

Schedule a quick guide tour