Essential concepts you need to know about React
Tags: react, beginners, javascript
Published: 2021-06-03 06:44:27

I've been using React for a couple of years now but when I started learning it I didn't pay too much attention to what React does for me, like what React abstracts through its API and why do I need to use JSX to build components, or why do we need Babel and so on. So if you're starting learning React or working with it, you might find this post helpful to know about core concepts.

## JavaScript to React

Let's say we don't have any React library out there, we just have vanilla JavaScript and we need to create a simple page that only contains the text "I'm learning React Fundamentals"  in a `div`  DOM node into the div with id root created.

```jsx
<html>
  <body>
    <div id="root"></div>
  </body>
</html>
```

Steps:

1. Create the `div` HTML element using [document.createElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) where we can pass as argument the `div` as a tagName  
2. Add the text "I'm learning React Fundamentals". We can use [textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent) for it.
3. Insert that created element into the document using [Append](https://developer.mozilla.org/en-US/docs/Web/API/Element/append) 

```html
<html>
  <body>
    <div id="root"></div>
		<script type="module">
		  const rootElement = document.getElementById("root")
		  const element = document.createElement("div")
			element.textContent = "I'm learning React Fundamentals"
		  rootElement.append(element)
		</script>
  </body>
</html>
```

So we'll get :

```html
<html>
  <body>
    <div id="root">
			<div>I'm learning React Fundamentals</div>
		</div>
  </body>
</html>
```

Behind the scenes, this is what React does to create DOM nodes, in case you want to dig into it you  can take a look at [the React source code](https://github.com/facebook/react/blob/ee432635724d5a50301448016caa137ac3c0a7a2/packages/react-dom/src/client/ReactDOMComponent.js#L416). React abstracts this imperative browser API to give us a more declarative API to work with.

With that explained, we can say that for creating react applications for the **web** we need:

- React: Help us to create **react** elements similar to creating an element in browser with `document.createElement`
- React DOM: Help us to render **react** elements to the DOM similar to `append`

## Using Raw React APIs

Now, let's create the same page we did before with Vanilla JavaScript but using React library. For that, we need to add external scripts so I'm gonna use `unpkg` which is a cdn for everything on npm, so we can add just the url and we'll load the files for React and React DOM.

Steps:

1.  Create a React element using [createElement](https://reactjs.org/docs/react-api.html#createelement) which receives these params :
    - **type** : It can be a type of element, can be a string like `div`, `span`, etc or a React Component(which is usually a class or a function), or can be a React Fragment type
    - **props** : An object containing properties
    - [...**children] :**  It can be a string (will be interpreted as text), or reference to other components that will allow us to nest elements. The rest from the third param is going to be the children.  Take in mind that, `children` is a special prop in React

2. Render React Element to the DOM using [ReactDOM.render](https://reactjs.org/docs/react-dom.html#render) which receives these params:
    - **element :** A React element
    - **container :** DOM node where the element will be inserted into

```html
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/react@17.0.0/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@17.0.0/umd/react-dom.development.js"></script>
  <script type="module">
		const rootElement = document.getElementById('root')
    const element = React.createElement(
			'div',
			{ className: "container" },
			"I'm learning React Fundamentals"
		)
    ReactDOM.render(element, rootElement)
  </script>
</body>
```

Now, Imagine that we want to render a list of fruit like using raw React API : 

```html
<div>
	<p>List of my favorite fruits</p>
	<ul>
	  <li>Apple</li>
	  <li>Orange</li>
	</ul>
</div>
```

That would be like: 

```jsx
const rootElement = document.getElementById('root')
const element = React.createElement('div', null,
  [
    React.createElement('p', null, 'List of my favorite fruits'),
    React.createElement('ul', null, 
			React.createElement('li', null, 'Apple'),
			React.createElement('li', null, 'Orange'),
		),
  ],
})

ReactDOM.render(element, rootElement)
```

Does that look easier to understand to you? It might be but imagine using React in this way in large applications. It can be hard to read and maintain so that's when comes `JSX` which is a HTML-like syntactic sugar on top of raw React API's. 

## Using JSX

JSX is not JavaScript which means that the browser will not understand natively so we need to use a code compiler such as `Babel` that will transform into standard Javascript 

You can play around [here to see how babel complies JSX to JavaScript](https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&build=&builtIns=App&corejs=3.6&spec=false&loose=false&code_lz=MYewdgzgLgBApgGzgWzmWBeGAeAFgRhmAQEMIIA5E1DAIigEsolaA-ASRgBkQA3OGACU4JYFACE2APQFWAKCA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=react&prettier=true&targets=&version=7.14.4&externalPlugins=)

```jsx
const element = <h1 className="title">I Love React!</h1>

// ↓ ↓ ↓ ↓ compiles to ↓ ↓ ↓ ↓

const element = React.createElement(
  "h1",
  {
    className: "title"
  },
  "I Love React!"
);
```

As demonstrated, JSX provides us a concise and familiar syntax for defining a tree structure that doesn't require learning a templating language or leaving javascript. Although you need to be aware of [JSX Gotchas](https://reactjs.org/docs/jsx-in-depth.html) like: 

- **User-Defined Components must be capitalized**: When the react element starts with a lowercase letter, it'll take as a built-in component like `span`, `div`, `h1`. So let's say you create a `titlepage` component

```jsx
function titlepage({children}) {
  return <h1 className="title">{children}</h1>
}

function App(){
	return(
		<div>
			<titlepage>My first blog!</titlepage>
		</div>
	)
}

// ↓ ↓ ↓ ↓ compiles↓ ↓ ↓ ↓

function titlepage(_ref) {
  var children = _ref.children;
  return React.createElement("h1", {
    className: "title"
  }, children);
}

var element = React.createElement("div", 
	null, 
	React.createElement("**titlepage**", null, "Hello World"));

// => ⚠️ titlepage is parsed as a string and doesn't take as a component/function
```

 Plus, you'll get an error in your console  and it'll suggest you name it starting with an uppercase letter

```jsx
// Error: The tag <titlepage> is unrecognized in this browser. 
// If you meant to render a React component, start its name with an uppercase letter.
```

 

## Final Notes

I would encourage you to  spend some time with the source code in React, play around with JSX in the [online babel REPL](https://babeljs.io/repl#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&build=&builtIns=App&corejs=3.6&spec=false&loose=false&code_lz=MYewdgzgLgBApgGzgWzmWBeGAeAFgRhmAQEMIIA5E1DAIigEsolaA-ASRgBkQA3OGACU4JYFACE2APQFWAKCA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=react&prettier=true&targets=&version=7.14.4&externalPlugins=) to see the compiled version of that code, so you can be better at understanding, reading and using it. Knowing what the abstraction does, will make you more effective to use it. 

Here are a few miscellaneous link related that help me to understand behind the scenes of  React

- [13 things you need to know about React](https://hackernoon.com/13-things-you-need-to-know-about-react-d2e6a6422552)
- [Fun with React Elements and JSX](https://medium.com/@singhsourav206/playing-with-react-elements-c262d345c130)
- I would recommend to take [EpicReact course](https://epicreact.dev) by Kent C. Dodds

Hope you enjoyed it. Thanks for reading!

... As always, enjoy your process of learning 🚀

Feel free to [reach out](https://paulccari.com/) if you wanna chat about anything.