Core building blocks of React
Tags: react, webdev, beginners, javascript
Published: 2020-02-17 20:06:43

Hello DEV community!

Every time I start learning something new I always do a short list of main concepts in order to have it handy when diving deeper into other concepts. It really always comes in handy!

I started learning React few weeks ago and since then I committed that I will learn something new everyday and also, I decided that I will document this journey by sharing my own understandings and knowledge :)

This article is all about the core building block of React, such as:
<ul>
<li>JSX</li>
<li>Components</li>
<li>State and props</li>
<li>Conditional rendering</li>
</ul>

So, let's start!

<h3><b>JSX</b></h3>
Before starting to discussing any concept of React, we must always remember that everything in react is JS (JavaScript) even if doesn't look like it!

```javascript 
var jsx_element = <h1>hi!</h1>;
```
The variable declaration above, doesn't look either like HTML nor like JS, right?

That is because JSX is used, which is a syntax extension to JS, and in the end it all compiles to JS code using Babel (compiler for next-gen JS). Therefore, we can use any JS expressions such as variables, getting object properties or even calling functions within JSX code by enclosing it in curly braces <b>'{}'</b>. 

```javascript
var address = {
  street: 'oxford street',
  number: 14,
  postcode: '3344'
  city : 'London'
  country: 'England'
}

const getAddress({street, number}) {
   return street + ' ' + number;
}


const jsx_element = <div>
                        <h1>{getAddress(address)}</h1>
                    </div>;

ReactDOM.render(
  jsx_element,
  document.getElementById('root')
);
```
You can notice on the example above that the curly braces are used in order to fetch the address in as string type by calling the getAddress function within the JSX code.


<h3><b>Components</b></h3>

Components is a concept that helps to enforce the single-responsibility principle in React. We should think of components as reusable pieces of our application, where each one performs (ideally) exactly one responsibility/task. In simple words, a component is a function that accepts data (props) and specifies how those data should appear in UI.

A component can be either a class-based or a function-based.

<h5><b>Class-based</b></h5>
A class-based component is also known as a stateful component or container component and it is created as follows:
```javascript
import React, Component from 'react';

class App extends Compoenent {
   render() {
     return(
       /* <div>JSX</div> */
      )
   }
}
exports default App;
```
<h5><b>Function-based</b></h5>
They are called function-based because they are literally JavaScript functions. Also, these types of components are also referred as stateless or representational components (originally!) because they are best used to only display UI. 
```javascript
import React from 'react';

const App = () => {
    return(
     /* <div>JSX</div> */
    )
}
exports default App;
```
The example uses a ES6 syntax, but a typical function is also a correct way of creating one. At the end, React is all JavaScript! Ideally, for performance reasons in a React app we should have few stateful components that manipulate state often, and many stateless components that only accept props and show UI.

Also, important to note that a function-based component can also be used as a stateful component. In simple words, Hooks enable the component to access the state by importing and using the useState (check out the resources to learn more).

<h3><b>State and props</b></h3>
<h5><b>Props</b></h5>
Passing data from one component to the other is done through properties or as known in React props. Meaning that, when a custom (not a DOM tag) component is used we can pass data to it by adding custom attributes to it. React passes the attribute to the component as an object where the attribute name is the key and it assigns to it the given value, e.g:
```javascript
const App = () => {

  return (
    <div> <Person name="Tringa" lastName="Krasniqi"/> </div>
  );

}
//it is actually passed as object
const Person = (props) => {
 /*
   props = {
      name : "Tringa",
     lastName : "Krasniqi"
  }
*/
}

```
Important to note:

- props are READ-ONLY and should never be modified (that's where state comes in!).
- all react components should act like pure functions with respect to their props.

<h5><b>State</b></h5>

State allows components to change the output when a user action has taken place, or when we receive recent network data etc., without violating the above-mentioned rule. State properties are private and fully controlled by the component. Therefore, local and encapsulated within the component. When the state is changed in a component React triggers DOM render and updates the value in UI.

To use state correctly means that the following need to be followed:

- it should not be modified directly:
```javascript
//(or this.props.name, if the data is passed)
this.state.name = "Tringa" //incorrect, although correct only when initialised in the constructor

setState({name: "Tringa"}) // correct
```
- state updates might be async, so many setStates will be run in batch and overriding the data. Therefore, use a function within the setState instead of an object, for e.g.:
```javascript
setState((state, props) => {
  //old state
  //new data (notice, it is props)
}) 
```
- state updates are merged, so when calling it multiple times it replaces the specified data and merges them to the rest of the properties of the state object. E.g:
```javascript
this.state = {
   name : "Tringa",
   lastName : "Krasniqi",
   age : 24
}

setState({ name : "Jane" });
setState({ lastName : "Doe" });


/* 
results in:
state = {
   name : "Jane",
   lastName : "Doe",
   age : 24
}
*/
```
<h3><b>Conditional rendering</b></h3>
It is often needed in our application to show or hide various UI elements based on the state of the application. One common example would be:

- when user is logged out, the profile view should redirect to login form
- when the user is logged in, it should show the profile view with their info

To achieve this in React we use the JavaScript conditional if statement or ternary operator within the JSX code. Using the if statement example:
```javascript
render() {
   const button = <LogginButton onClick={this.handleLogin}/>

   if(this.state.isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogout}/>
   } 
   return (
     <div>
         {button}
     </div>

    );
}
```
The ternary operator is the short form of writing if conditional statements in one line of code, however it is not as readable as its long form. The syntax of this operator is:
```javascript
condition ? expressionIfTRUE : expressionIfFALSE;

//and it is the same as:

if(condition) {
   expressionIfTRUE;
} else {
   expressionIfFALSE;
}
```
In our React case it would be used like in the following case:
```javascript
render() {
   return(
    <div>
    {
      this.state.isLoggedIn ? 
      <LogoutButton onClick={this.handleLogout}/>
      :
      <Logginbutton onClick={this.handleLogin}/>
    }

    </div>
   )
}
```
<h3><b>Apart from these, what's next?</b></h3>

Resources to learn more form:
- React documentation https://reactjs.org/docs/getting-started.html
- React course https://www.udemy.com/course/react-the-complete-guide-incl-redux/
- Component lifecycle https://www.freecodecamp.org/news/these-are-the-concepts-you-should-know-in-react-js-after-you-learn-the-basics-ee1d2f4b8030/
- Beginners guide https://dev.to/aspittel/a-complete-beginners-guide-to-react-2cl6
- React Hooks https://reactjs.org/docs/hooks-intro.html | https://reactjs.org/docs/hooks-reference.html 

Other important concepts to learn:
- Component lifecycle
- Styling components
- React Hooks

Hope this article will help anyone that is on the same journey of learning React as me.

Any feedback/suggestion/correction will be highly appreciated.

Thank you for reading!