React Concepts

Rajkumar
4 min readDec 20, 2021

Core building blocks of React

#react#webdev#beginners#javascript

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>;

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')
);

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;

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;

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>
);
}

const Person = (props) => {

}

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
  • 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)
})
  • 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
}
*/

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>
);
}

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;
}

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

Apart from these, what’s next?

Resources to learn more form:

--

--