Nekode
React

React basic concept

Learn some of react basic concepts like JSX, Component, State and others

Rifki ahmad fahrezi

Rifki ahmad fahrezi

Introduction

On this article we will learn about React basic concepts, including JSX, Component, state and props, without any further do, scroll a little bit more to start learning 🤙.

What is JSX

JSX (Javascript XML) is a syntax extension for Javascript, JSX allows you to write HTML elements in Javascript, using JSX in react is not mandatory, but using JSX it will make the development process alot easier in read and writing codes.

// Using JSX
const ele = <h1>This is sample JSX</h1>;
 
// Using plain JavaScript
const ele = React.createElement('h1', null, 'This is sample JSX');

How JSX works

JSX is not a valid Javascript or HTML syntax, so browser cannot read JSX files directly. So JSX need a transpiler to convert JSX to javascript, after transpiled then JSX can be executed by the browser.

The transpile process occurs on build process, so the browser will never know that this website using JSX. The browser will only receive a tree of objects that have been described using the React API.

// This is JSX
const ele = <h1>This is sample JSX</h1>;
 
// This is the transpiled result
const ele = React.createElement('h1', null, 'This is sample JSX');

Benefits of using JSX

  • Improved Readability: JSX’s HTML-like syntax makes your code more readable and easier to understand.
  • Component-based Structure: JSX fits naturally with React’s component-based architecture, making it easy to see the structure and hierarchy of components.
  • Enhanced Developer Experience: With JSX, you get better error messages and warnings during development, which helps in debugging and maintaining the code.

What is a component

Component is an independent and reusable bits of code, in React application that define what gets displayed on the UI.

Component are basically a function, but instead returning a value component returning a UI, the same like function component also can have an input (in function is a arguments) called props. The idea of using component is the same like using function, to make your code more reusable. And you have to note that one component only responsible to one thing.

Class component

Class component is a ES6 classes that extended with React.Component. Here is an example of making component using class component:

import React from 'react'
 
class Hello extends React.Component {  
		render() {
		    return <h1>Hello Nekode!</h1>;  
		}
}

using Class component is an old way to make a component, now React prefer us to create a component using functional component.

Functional component

Functional component are a lot simpler than class component, They are like regular javascript function but its return an HTML elements, with functional component you can use React hooks like manage state and lifecycle events. Example functional component:

import React from 'react'
 
function Hello(){
	return (
		<h1>Hello Nekode!</h1>
	)
}

Rendering a component

Like mentioned above component is like a function, instead of returning a value its return an UI or HTML elements. So to call a function we need to use the round brackets after name of the function.

hello()

Instead of using round brackets, to call or render a component you need to use </> just like HTML element.

<Hello/>

Tips: Component name are written using the PascalCase rule, where every first character of the first word must be uppercase and the rest of it is lower case, example: HelloWorld

State and Props

State is plays important role in React, State can used to create an interactive and dynamic web application. State in React refers to an object that can stores a value or data, also state can determines how the component behaves.

Whenever the state changes, React will re-render the component to reflect the updated data. This will make you can build a dynamic UI and interaction that response to user interaction.

Create a state

Creating a state is essential to building dynamic and interactive components. We can create a state using the Class component or functional component.

Create state in a class component

You can create a state using a class component by using this.state inside a constructor

import React from 'react';
 
class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: 'Nekode', // Example property in the state
        };
    }
 
    render() {
        return (
            <div>
                <h1>My Name is {this.state.name}</h1> {/* Call the state */}
            </div>
        );
    }
}

Create state in a functional component

You can create a state in functional component bu using one of the React hooks which is useState.

import React, { useState } from 'react'
 
function MyComponent(){
	const [name, setName] = useState("Nekode") 
	// [name of the state, setter state] = useState(your initial state value)
 
	return (
		<h1>Hello!, my name is {name}</h1>
	)
}

There is no restrictions of what kind of value on the state that you want to store, you can use number, string, array or even an object.

Updating state

To make your website more dynamic and interactive you can update your state value on some user interaction like on click or anything.

Updating state in a class component

In class component you can use this.seState method to update your state, here is an example of a counter app that will increase the number by click the button in class component.

import React from "react";
 
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0, // set initial state value
        };
    }
		// method to increment the state value
    increment = () => {
		    // set the previous state value to add + 1
        this.setState((prevState) => ({
            count: prevState.count + 1,
        }));
    };
 
    render() {
        return (
            <div>
                <h1>
                    The current count is :{" "}
                    {this.state.count} {/* render current state value */}
                </h1>
                {/*make event on click for increment state value*/}
                <button onClick={this.increment}>
                    Increase
                </button>
            </div>
        );
    }
}

Result

Simple counter with react

Exercise: create a method and an event handler to decrease the state value on every decrease button clicked

Updating a state in a functional component

Again, using functional component are a lot simpler than class component, here is the same counter app code but in functional component

import React, { useState } from 'react'
 
function MyComponent(){
	const [counter, setCounter] = useState(0) 
 
	return (
		<h1>The current count is {counter}</h1>
		<button onClick={() => setCounter(prev => prev + 1)} >
			Increase
		</button>
	)
}

Props

Like you already know component is just like a function, so component also can get an input from props (in function called arguments).

Using Props in Class Components

To use props in a class component, you access them through this.props.

import React, { Component } from 'react';
 
class Welcome extends Component {
  render() {
    return (
      <div>
        <h1>Hello, {this.props.name}!</h1>
      </div>
    );
  }
}
 
export default Welcome; // export component so it can be use on another component

Explanation:

  1. The Welcome component receives a name prop from its parent.
  2. Inside the render method, the name prop is accessed using this.props.name.
  3. The value of the name prop is displayed dynamically in the component.

Using Props in Functional Components

In functional component you can access props directly as function arguments.

import React from 'react';
 
function Welcome(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
    </div>
  );
}
 
export default Welcome; // export component so it can be use on another component

Props usage

import React from 'react';
import Welcome from './Welcome'; // import the component
 
function App() {
  return (
    <Welcome name="Nekode" /> {/* pass the props to component */}
  );
}
 
export default App;

Props tips

To make the code cleaner, you can destructure props in both class and functional components.

  • Class component

    class Welcome extends Component {
      render() {
        const { name } = this.props; // destruct props here
        return (
          <div>
            <h1>Hello, {name}!</h1>
          </div>
        );
      }
    }
  • Funtional component

    function Welcome({ name }) { // destruct props here
      return (
        <div>
          <h1>Hello, {name}!</h1>
        </div>
      );
    }

Conclusion

Understanding React basics like JSX, components, state, and props is key to building dynamic web apps. JSX simplifies UI creation, components promote reusability, state manages dynamic data, and props enable communication between components. Master these fundamentals to confidently explore advanced React features and create interactive, scalable interfaces. Keep practicing and enjoy the process!