React for Beginners

Sep 5, 2021

React is a user interface library open-sourced by Facebook in 2013. Even though React has criticized at first, it gained momentum in time. Today React is the most popular UI library. In fact, Crudful's frontend is a React application too.

This guide will bring you up to speed by going over core React principles and their use cases.

JSX

JSX is an extension to JavaScript that makes it easier to describe user interfaces. Even though using JSX for React is entirely optional, it is considered standard practice.

JSX allows us to assign JavaScript variables to HTML elements. These variables are called React elements. Moreover, we can put JavaScript expressions inside these elements.

// React element
const paragraph = <p>React is cool!</p>;
// React element with JavaScript expression
const otherLibrary = "Vue.js";
const otherParagraph = <p>{otherLibrary} is cool too!</p>;

JSX has more impressive features that bring JavaScript's power to user interfaces. We will check them in the following sections.

Components

Components are the building blocks of user interfaces in React. They can be defined as simple JavaScript functions.

Let's create a component that displays cool frontend libraries in the universe.

// React component returning a React element
function CoolLibrary(props) {
return <p>React is cool!</p>;
}
// Find the HTML element with `id="root"` and render `CoolLibrary` component
ReactDOM.render(<CoolLibrary />, document.getElementById("root"));

As we can see from the code above, React components accept a single argument called props (short for "properties") and render elements accordingly.

Let's improve CoolLibrary component to display cool libraries dynamically.

// React component returning a React element
function CoolLibrary(props) {
return <p>{props.name} is cool!</p>;
}
// Find the HTML element with `id="root"` and render `CoolLibrary` component
// Note the `name` attribute
ReactDOM.render(<CoolLibrary name="Vue.js" />, document.getElementById("root"));

Since we used {props.name} inside CoolLibrary component, we can display any cool library we want.

React component attributes are passed to props parameter as a JavaScript object. For example, if we console log props inside CoolLibrary, we get the following:

// [object Object]
{
"name": "Vue.js"
}

Considering props is just a JavaScript object, we can use object destructuring to improve code readability.

// React component returning a React element
// Note the object destructuring `props -> {name}`
function CoolLibrary({name}) {
return <p>{name} is cool!</p>;
}
// Find the HTML element with `id="root"` and render `CoolLibrary` component
// Note the `name` attribute
ReactDOM.render(<CoolLibrary name="Vue.js" />, document.getElementById("root"));

Another nice thing about React components is their composability. We can build component trees with unlimited depth. Let's create a component named LibraryList to list cool libraries.

// React component returning a React element
// Note the object destructuring `props -> { name }`
function CoolLibrary({ name }) {
return <p>{name} is cool!</p>;
}
// React component consist of another React component
function LibraryList(props) {
return (
<div>
<CoolLibrary name="React" />
<CoolLibrary name="Vue.js" />
<CoolLibrary name="Angular" />
</div>
);
}
// Find the HTML element with `id="root"` and render `LibraryList` component
ReactDOM.render(<LibraryList />, document.getElementById("root"));

Let's go one more step and make LibraryList more powerful. As React components accept array values as props, we can create CoolLibrary component for each array value without code duplication.

// React component returning a React element
// Note the object destructuring `props -> { name }`
function CoolLibrary({ name }) {
return <p>{name} is cool!</p>;
}
// React component consist of another React component
// `LibraryList` accepts an array called `libraries`
// and renders `CoolLibrary` components inside a `div`
function LibraryList({ libraries }) {
return (
<div>
{libraries.map((library) => (
<CoolLibrary name={library} />
))}
</div>
);
}
// Find the HTML element with `id="root"` and render `LibraryList` component
ReactDOM.render(
<LibraryList
libraries={["React", "Vue.js", "Angular", "Svelte", "Ember.js"]}
/>,
document.getElementById("root")
);

Events

Our LibraryList and CoolLibrary components successfully list cool library names. Let's add some interactivity by allowing users to like libraries.

As you can see from the code below, handleClick function is called when any button is clicked. Since we added button inside CoolLibrary, each alert displays the related library name.

// React component returning a React element
// Note the object destructuring `props -> { name }`
function CoolLibrary({ name }) {
// `onClick` event handler
function handleClick() {
alert("You liked " + name);
}
return (
<p>
{name} is cool! <button onClick={handleClick}>Like</button>
</p>
);
}
// React component consist of another React component
// `LibraryList` accepts an array called `libraries`
// and renders `CoolLibrary` components inside a `div`
function LibraryList({ libraries }) {
return (
<div>
{libraries.map((library) => (
<CoolLibrary name={library} />
))}
</div>
);
}
// Find the HTML element with `id="root"` and render `LibraryList` component
ReactDOM.render(
<LibraryList
libraries={["React", "Vue.js", "Angular", "Svelte", "Ember.js"]}
/>,
document.getElementById("root")
);

React handles DOM events through an abstraction called SyntheticEvent to have consistent behavior between different browsers. All supported events can be found here.

State

Handling the state can be tricky for most frontend applications. React handles this complexity by splitting applications into self-sufficient and reusable components.

There are two main values that affect the output of a component:

  1. props (or "properties") are passed to the components from outside (for example, name in CoolLibrary).
  2. Local states in a component (for example, likes in CoolLibrary)

React watches changes to these values and re-renders components accordingly. Let's display the number of likes for each cool library, change their values with button clicks and see re-renders in action.

// React component returning a React element
// Note the object destructuring `props -> { name }`
function CoolLibrary({ name }) {
// create a local state for number of likes
const [likes, setLikes] = React.useState(0);
// `onClick` event handler
function handleClick() {
setLikes(likes + 1);
}
return (
<p>
{name} is cool and it has {likes} likes!{" "}
<button onClick={handleClick}>Like</button>
</p>
);
}
// React component consist of another React component
// `LibraryList` accepts an array called `libraries`
// and renders `CoolLibrary` components inside a `div`
function LibraryList({ libraries }) {
return (
<div>
{libraries.map((library) => (
<CoolLibrary name={library} />
))}
</div>
);
}
// Find the HTML element with `id="root"` and render `LibraryList` component
ReactDOM.render(
<LibraryList
libraries={["React", "Vue.js", "Angular", "Svelte", "Ember.js"]}
/>,
document.getElementById("root")
);

React.useState function accepts initial value for a state (for example, 0 for likes) and returns state variable (for example, likes) and its setter function (for example, setLikes). Moreover, when we change the number of likes calling setLikes function, React detects the change and re-renders related components.

Summary

React has some unusual concepts considering other frontend libraries, so it is crucial to take your time to understand these ideas.

We believe the best way to improve your React expertise is building sample projects with it. For example, you can build React components for a blog page (this page has ContentHeader, ContentCard and ContentP)!

We will publish more detailed guides on React, follow @crudfulcom and join Discord server for more!