React JavaScript Examples

React is a library developed by Facebook, now known as Meta, specifically for its own platform. However, due to its widespread popularity and the benefits it offers for building user interfaces in web applications, it was released as open source. React is particularly renowned for enabling the development of single-page web applications, which means that the entire application is loaded just once. This library is regarded as the most robust option for JavaScript when it comes to constructing web application interfaces. The advantages of using React include its component-based architecture and its capability to virtually manipulate the document object model. Consequently, React has become the most sought-after JavaScript library in contemporary web development.

How to get started?

To begin utilizing React, it is essential to establish the development environment. While we can manually create files and directories and install the required modules, the most straightforward and efficient method is to employ Create React App. This command serves as a utility for initializing a new React project, complete with a conventional configuration and structure. The following commands will facilitate the project setup, with the final command launching the development server to run the project locally.

Example

npx create-react-app my-app
cd my-app
npm start

React Basic Examples:

Let’s explore several fundamental examples of React syntax, where we will delve into essential topics that serve as crucial building blocks for crafting React code and comprehending how React operates within JavaScript.

1. Component Structure

In React, the user interface is created using components, which serve as the fundamental building blocks of a React application. These components can be defined either as JavaScript functions or as classes. A functional component is a straightforward function that accepts props (short for properties) as its argument and produces a React element, representing what is intended to be rendered on the display.

Example:

Example

import React from 'react';

// Functional component that receives props and returns a greeting message
function Welcome( props ) {
  return <h1> Hello, { props.name } </h1>;
}

export default Welcome;

2. Class Components

Class components serve as an additional approach to defining components in React. They offer greater capabilities compared to functional components, as they encompass lifecycle methods and manage state. A class component is defined using ES6 class syntax, extending React.Component, and must implement a render method that returns a React element.

Example:

Example

import React, { Component } from 'react';

// Class component that renders a greeting message
class Welcome extends Component {
  render() {
    return <h1> Hello, { this.props.name } </h1>;
  }
}

export default Welcome;

3. State Management

In React components, the state is a distinctive property that contains data which may be subject to change over time. Class components manage state through this.state, and updates to the state can be performed using this.setState. By managing state, components are able to respond to user interactions and various events by re-rendering with the modified data.

Example:

Example

import React, { Component } from 'react';

class Counter extends Component {
  constructor( props ) {
    super( props );
    // Initializing the state with a count of 0
    this.state = { count : 0 };
  }

  // Method to increment the count
  increment = ( ) => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p> Count : { this.state.count }</p>
        {/* Button for triggering the increment method */}
        <button onClick = { this.increment } > Increment </button>
      </div>
    );
  }
}

export default Counter;

4. Functional Components with Hooks

Hooks were introduced in React version 16.8 and enable functional components to harness state management and other features available in React. The useState hook is specifically designed to incorporate state within a functional component. By utilizing hooks, functional components gain enhanced capabilities, allowing them to handle state and execute side effects effectively.

Example:

Example

import React, { useState } from 'react';

function Counter() {
  // useState hook to manage the count state
  const [ count, setCount ] = useState( 0 );

  return (
    <div>
      <p> Count : { count } </p>
      {/* Button to increment the count state */}
      <button onClick = { () => setCount( count + 1 )} > Increment </button>
    </div>
  );
}

export default Counter;

5. Effect Hook

The useEffect hook is employed to manage side effects in functional components, such as retrieving data, updating the DOM, and establishing subscriptions or timers. It serves to replicate the lifecycle methods found in class components. The primary goal of introducing the useEffect hook is to reduce the drawbacks associated with class-based components. For instance, activities such as updating the DOM, fetching data from API endpoints, and creating subscriptions or timers can lead to unintended side effects. Given that the render method is quick to produce a side effect, it becomes necessary to leverage lifecycle methods to monitor these effects.

Example:

Example

import React, { useState, useEffect } from 'react';

function DataFetcher() {
  const [ data, setData ] = useState( null );

  // useEffect hook to fetch data when the component mounts
  useEffect( ( ) => {
    fetch( ' https://api.logic-practice.com/data ')
      .then( response => response.json( ) )
      .then( data => setData( data ));
  }, [ ]); // Empty dependency array means this effect runs once after the initial render

  // Display loading message until data is fetched
  if ( !data ) {
    return <div> Loading . . . </div>;
  }

  // Display fetched data
  return <div> { JSON.stringify( data )} </div>;
}

export default DataFetcher;

6. Conditional Rendering

React allows for the selective rendering of components, enabling developers to determine which component to display on the interface based on specific criteria. This technique is referred to as conditional rendering. In React, conditional rendering operates similarly to how conditions function in JavaScript. You can utilize JavaScript control structures such as if statements or the ternary operator to create elements that reflect the current state, allowing React to refresh the user interface accordingly.

Example:

Example

import React, { useState } from 'react';

function Greeting() {
  const [ isLoggedIn, setIsLoggedIn ] = useState( false );

  return (
    <div>
      {/* Conditional rendering based on isLoggedIn state */}
      { isLoggedIn ? <h1> Welcome back! </h1> : <h1> Please sign in. </h1>}
      {/* Button to toggle the isLoggedIn state */}
      <button onClick = { ( ) => setIsLoggedIn( !isLoggedIn ) }>
        { isLoggedIn ? ' Logout ' : ' Login ' }
      </button>
    </div>
  );
}

export default Greeting;

7. Lists and Keys

In React, the concepts of lists and keys are essential building blocks. Lists serve the purpose of presenting data in a structured manner and are commonly employed to display menus on websites. In React, the creation of lists follows the same principles as constructing lists in JavaScript. A key functions as a unique identifier. Within React, it plays a crucial role in determining which items have been altered, updated, or removed from the lists. This is particularly beneficial when components are generated dynamically or when users interact with the lists. Additionally, it aids in identifying which components within a collection require re-rendering, rather than re-rendering the entire set of components every time.

Example:

Example

import React from 'react';

function ItemList( props ) {
  const items = props.items;
  return (
    <ul>
      {/* Map over items and render a list item for each, providing a unique key */}
      { items.map( item => (
        < li key = { item.id } > { item.name } </li>
      ))}
    </ul>
  );
}

export default ItemList;

8. Forms and Controlled Components

In React, controlled components manage form data via their internal state, acquiring values through props and updating them through callback functions such as onChange. The parent component maintains the state and conveys the modified values as props to the controlled component. Form elements, whether they are text inputs or selections, initiate state changes and refresh by invoking functions upon changes.

Example:

Example

import React, { useState } from 'react';

function NameForm() {
  const [ name, setName ] = useState(' ');

  // Handler to update the name state on input change
  const handleChange = ( event ) => {
    setName( event.target.value );
  };

  // Handler to alert the submitted name and prevent default form submission
  const handleSubmit = ( event ) => {
    alert( ' A name was submitted : ' + name );
    event.preventDefault();
  };

  return (
    <form onSubmit = { handleSubmit } >
      <label>
        Name:
        {/* Input element controlled by the name state */}
        <input type = " text " value = { name } onChange = { handleChange } />
      </label>
      <button type = " submit " > Submit </button>
    </form>
  );
}
export default NameForm;

9. Composing Components

The architecture of components in React necessitates the inclusion of at least one component within a standalone component, with each sub-component having the capacity to contain additional components. In React, components serve as fundamental units employed to construct user interfaces.

Example:

Example

import React from 'react';

function Avatar( props ) {
  // Avatar component renders user's avatar image
  return (
    <img src = { props.user.avatarUrl } alt = { props.user.name } />
  );
}

function UserInfo( props ) {
  // UserInfo component renders user information and uses the Avatar component
  return (
    <div className = " UserInfo ">
      <Avatar user = { props.user } />
      <div className = " UserInfo ? name ">
        { props.user.name }
      </div>
    </div>
  );
}

function Comment( props ) {
  // Comment component composes UserInfo and other elements
  return (
    <div className = " Comment " >
      <UserInfo user = { props.author } />
      <div className = " Comment ? text ">
        { props.text }
      </div>
      <div className = " Comment ? date ">
        { props.date }
      </div>
    </div>
  );
}
export default Comment;

React Project Examples

We have explored fundamental syntax illustrations and the methodology for composing React code on crucial subjects such as state management, components, forms, lists, keys, and Hooks. Now, let us delve into more detailed examples that are regarded as projects and significant React tasks frequently encountered in interviews and practice React exercises. Engaging in these exercises will enhance our comprehension of React more effectively.

1. React Counter App

A React counter application is a program that enables users to interact with a numeric counter value. It illustrates fundamental state management and user interaction within a user interface. To create a basic counter application in React, you should initiate a useState variable called count and implement setCount to modify the state. Create two buttons labeled increment and decrement that adjust the count state by +1 and -1, respectively. Link these buttons to setCount through event handlers.

Counter Component - Counter.js

Example

// src/Counter.js
import React, { useState } from 'react';

function Counter() {
  const [ count, setCount ] = useState(0);

  const increment = () => {
    setCount( count + 1 );
  };

  const decrement = () => {
    setCount( count-1 );
  };

  return (
    <div style={{ textAlign: ' center ', marginTop : ' 50px ' }}>
      <h1> React Counter App </h1>
      <h2> { count } </h2>
      <button onClick = { increment } style = {{ marginRight : ' 10px ', padding : ' 10px ', fontSize : ' 16px ' }}>Increment</button>
      <button onClick = { decrement } style = {{ padding : ' 10px ', fontSize : ' 16px ' }}> Decrement </button>
    </div>
  );
}

export default Counter;

Main Component - App.js

Example

// src/App.js
import React from 'react';
import './App.css';
import Counter from './Counter';

function App() {
  return (
    <div className = " App " >
      <Counter />
    </div>
  );
}

export default App;

This component (Counter) represents a simple counting application created using React.

It imports the useState hook from React to manage the state.

The state variable named count, along with the function setCount, is established through the useState hook, which is initialized with a value of 0.

Two functionalities, augmentation and decrement, are defined to update the count state whenever the associated buttons are pressed.

The return statement includes JSX that constructs the user interface for the counter application.

It includes the h1 header that displays "React Counter Application".

The current value of count is displayed using an h2 element.

There are two buttons labeled "Increment" and "Decrement," which are designed to increase and decrease the value of the counter respectively.

The onClick event handlers are assigned to the increment and decrement functions to update the counter whenever the buttons are clicked.

Inline styles are utilized to enhance the emphasis on the content and provide definition to the top section of the element.

Adding Styles - App.css

Example

/* src/App.css */

.App {
  font-family: sans-serif;
  text-align: center;
}

button {
  margin: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

Project Structure :

Example

react-counter/
├── node_modules/
├── public/
│   ├── index.html
│   └── ...
├── src/
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── Counter.js
│   ├── index.css
│   ├── index.js
│   ├── logo.svg
│   └── serviceWorker.js
├── .gitignore
├── package.json
├── README.md
└── yarn.lock

Output:

2. Submission Form

Creating a Form in React involves the use of JSX elements. We will leverage a functional component to display these elements. Various HTML elements will be created as part of this project. To implement the design, we will apply CSS for styling. Managing forms primarily revolves around how you manage the data as it changes or when it is submitted. While in HTML, form data is usually managed by the Document Object Model (DOM), in React, form data is typically handled by the components themselves.

Form Component - SimpleForm.js

Example

// src/ components/ SimpleForm.js
import React, { useState } from 'react';
import './SimpleForm.css';

function SimpleForm() {
  const [ name, setName ] = useState(' ');
  const [ email, setEmail ] = useState(' ');
  const [ submittedData, setSubmittedData ] = useState( null );

  const handleSubmit = ( event ) => {
    event.preventDefault( );
    // Store the submitted form data in an object
    const formData = {
      name: name,
      email: email
    };
    // Set the submitted data in the below state
    setSubmittedData( formData );
  };

  return (
    <div className = " form-container ">
      <h2> Simple Form </h2>
      <form onSubmit = { handleSubmit } >
        <div className = " form-group " >
          <label htmlFor = " name " > Name: </label>
          <input 
            type = " text " 
            id = " name " 
            value = { name } 
            onChange = { ( event ) => setName( event.target.value )} 
            required 
          />
        </div>
        <div className = " form-group " >
          <label htmlFor = " email " > Email: </label>
          <input 
            type = " email " 
            id = " email " 
            value = { email } 
            onChange = {( event ) => setEmail( event.target.value )} 
            required 
          />
        </div>
        <button type = " submit " > Submit </button>
      </form>
      { submittedData && (
        <div className = " submitted-data " >
          <h2> Submitted Data </h2>
          <p> Name: { submittedData.name } </p>
          <p> Email: { submittedData.email } </p>
        </div>
      )}
    </div>
  );
}

export default SimpleForm;

SimpleForm is a React component designed for the purpose of generating a straightforward form. This file is tasked with importing React, the useState hook, and the relevant CSS for styling the form. The component predominantly utilizes the useState hook to oversee the state of the input fields, specifically for the name and email, as well as to manage the data that is sent upon submission. Upon submission of the form, the handleSubmit function is invoked. Additionally, it prevents the default action of form submission.

Main Component - App.js

Example

// App.js

import React from 'react';
import SimpleForm from './components/SimpleForm';

function App() {
  return (
    <div className = " App ">
      <SimpleForm />
    </div>
  );
}

export default App;

The App.js file serves as the primary component in React that handles the rendering output. It acts as the initial entry point for the form application. Within this component, the objective is to return a div element that encapsulates the simpleForm component inside it.

App styles - SimpleForm.css

Example

/* SimpleForm.css */

.form-container {
  width: 400px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input[type="text"],
input[type="email"] {
  width: 100%;
  padding: 10px;
  font-size: 16px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.submitted-data {
  margin-top: 20px;
}

CSS enhances the aesthetic quality of the application. This particular CSS file is designed to style buttons, input fields, and text areas. The primary elements that receive styling include labels, input fields, the section displaying submitted data, form groups, and buttons.

React Entry Point - index.js

Example

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

The index.js file serves as a component that brings in React and React DOM to facilitate the rendering of components. The App component will be displayed within the root element found in the HTML document.

Styles - index.css

Example

/* index.css */

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

.App {
  text-align: center;
  margin-top: 50px;
}

Project Structure :

Example

simple-form-app/
│
├── public/
│   ├── index.html
│   └── ...
│
└── src/
    ├── components/
    │   ├── SimpleForm.js
    │   └── SimpleForm.css
    ├── App.js
    ├── index.js
    └── index.css

Output:

Conclusion:

In our discussions, we have explored various instances of React along with its syntax, demonstrating how to effectively program using React JavaScript. The examples included a spectrum of topics, from fundamental concepts such as States, Props, and Hooks to more complex ideas like state management, component control, and form handling. Within the article, we examined two principal React project examples: the Counter and Form Submission applications. These examples are designed to facilitate a clearer understanding of React concepts in a more straightforward manner.

Input Required

This code uses input(). Please provide values below: