DEV Community

Cover image for Core building blocks of React
Tringa Krasniqi
Tringa Krasniqi

Posted on

Core building blocks of React

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:

  • JSX
  • Components
  • State and props
  • Conditional rendering

So, let's start!

JSX

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!

var jsx_element = <h1>hi!</h1>;
Enter fullscreen mode Exit fullscreen mode

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 '{}'.

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')
);
Enter fullscreen mode Exit fullscreen mode

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.

Components

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.

Class-based

A class-based component is also known as a stateful component or container component and it is created as follows:

import React, Component from 'react';

class App extends Compoenent {
   render() {
     return(
       /* <div>JSX</div> */
      )
   }
}
exports default App;
Enter fullscreen mode Exit fullscreen mode
Function-based

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.

import React from 'react';

const App = () => {
    return(
     /* <div>JSX</div> */
    )
}
exports default App;
Enter fullscreen mode Exit fullscreen mode

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).

State and props

Props

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:

const App = () => {

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

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

Enter fullscreen mode Exit fullscreen mode

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.
State

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:
//(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
Enter fullscreen mode Exit fullscreen mode
  • 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.:
setState((state, props) => {
  //old state
  //new data (notice, it is props)
}) 
Enter fullscreen mode Exit fullscreen mode
  • 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:
this.state = {
   name : "Tringa",
   lastName : "Krasniqi",
   age : 24
}

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


/* 
results in:
state = {
   name : "Jane",
   lastName : "Doe",
   age : 24
}
*/
Enter fullscreen mode Exit fullscreen mode

Conditional rendering

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:

render() {
   const button = <LogginButton onClick={this.handleLogin}/>

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

    );
}
Enter fullscreen mode Exit fullscreen mode

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:

condition ? expressionIfTRUE : expressionIfFALSE;

//and it is the same as:

if(condition) {
   expressionIfTRUE;
} else {
   expressionIfFALSE;
}
Enter fullscreen mode Exit fullscreen mode

In our React case it would be used like in the following case:

render() {
   return(
    <div>
    {
      this.state.isLoggedIn ? 
      <LogoutButton onClick={this.handleLogout}/>
      :
      <Logginbutton onClick={this.handleLogin}/>
    }

    </div>
   )
}
Enter fullscreen mode Exit fullscreen mode

Apart from these, what's next?

Resources to learn more form:

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!

Top comments (6)

Collapse
 
sabbin profile image
Sabin Pandelovitch

It should be specified that in functional components the state is available via useState hook and not with this
.state
. Also there should be some references to React Hooks due to the fact that that is the current way of doing things

Collapse
 
tringakrasniqi profile image
Tringa Krasniqi

Thank you a lot for your feedback :)

I tried my best to keep things as simple as possible and not mention Hooks or anything else and not explaining them. I implied that function-based components were originally created for display only (well, until Hooks came on the way). But, I will definitely add a link to React Hooks to anyone that is interested to know more.

Collapse
 
nyamador profile image
Desmond

Hi Tringa do you use `` backticks to enclose your code snippets in the markdown editor?

Collapse
 
tringakrasniqi profile image
Tringa Krasniqi • Edited

Hi Desmond :) Yeah I use the backticks and followed with javascript, like: javascript (three backticks)

Collapse
 
vaibhavkhulbe profile image
Vaibhav Khulbe

Nicely explained! Those resources are added bonus. 👏

Collapse
 
tringakrasniqi profile image
Tringa Krasniqi

So glad you enjoyed it ☺️