React Js

React JS Tutorial Learn React JS, the powerful JavaScript library for building dynamic and interactive user interfaces. This beginner-friendly tutorial covers core concepts like components, state, props, and hooks, with hands-on projects to create responsive web apps. Perfect for aspiring developers looking to master modern front-end development.

React ES6

24 April 2025 | Category:

Welcome to this beginner-friendly tutorial on using ES6 (ECMAScript 2015) with React JS! ES6 is a major update to JavaScript that introduces modern, concise syntax, making it easier to write clean and efficient React code. In this tutorial, you’ll learn key ES6 features commonly used in React, such as arrow functions, destructuring, modules, and template literals. We’ll apply these concepts by building a simple Task Tracker app to display and add tasks. By the end, you’ll understand how ES6 enhances React development and be ready to use it in your projects.


What is ES6?

ES6, also known as ECMAScript 2015, is a version of JavaScript that introduced powerful features to make coding more efficient and readable. React heavily relies on ES6 for its concise syntax and modularity, which streamline component creation and state management.


Why Use ES6 with React?

1. Cleaner Code

  • Arrow functions and destructuring reduce boilerplate.

2. Modularity

  • Import/export syntax organizes code into reusable modules.

3. Improved Readability

  • Template literals and concise methods make code easier to understand.

4. Modern Standard

  • Most React tutorials, libraries, and tools use ES6, making it essential for developers.

Prerequisites

Before starting, you should have:

  • Basic knowledge of React (components, JSX, props) and JavaScript.
  • Node.js and npm installed (download from nodejs.org).
  • A code editor like Visual Studio Code.
  • A terminal for running commands.

We’ll use Create React App to set up our project, which supports ES6 out of the box.


Key ES6 Features for React

Let’s explore the ES6 features you’ll use in React, with examples tailored to React development.

1. Arrow Functions

  • Arrow functions (=>) provide a concise syntax for writing functions and automatically bind this, which is useful in React for event handlers and callbacks.

Example:

// Traditional function
function handleClick() {
  console.log('Clicked!');
}

// Arrow function
const handleClick = () => console.log('Clicked!');

In React:

const Button = () => {
  const handleClick = () => alert('Button clicked!');
  return <button onClick={handleClick}>Click Me</button>;
};

2. Destructuring

  • Destructuring lets you extract properties from objects or arrays into variables, making prop handling in React cleaner.

Example:

// Without destructuring
function Task(props) {
  return <p>{props.title}</p>;
}

// With destructuring
function Task({ title }) {
  return <p>{title}</p>;
}

3. Modules (Import/Export)

  • ES6 modules allow you to split code into reusable files using import and export. React components are typically written as modules.

Example:

// Task.js
export const Task = ({ title }) => <p>{title}</p>;

// App.js
import { Task } from './Task';

4. Template Literals

  • Template literals (`) allow string interpolation with ${} for dynamic values, useful for displaying dynamic content in React.

Example:

const name = 'Alice';
const greeting = `Hello, ${name}!`; // "Hello, Alice!"

In React:

const Greeting = ({ name }) => <p>{`Hello, ${name}!`}</p>;

5. Spread Operator

  • The spread operator (...) copies or merges objects/arrays, often used in React for passing props or updating state.

Example:

const props = { title: 'Task 1', completed: false };
const Task = ({ title, completed }) => <p>{title}</p>;
<Task {...props} />; // Passes title and completed as individual props

6. Default Parameters

  • Default parameters set fallback values for function arguments, useful for optional props.

Example:

const Task = ({ title = 'No Task' }) => <p>{title}</p>;

Setting Up the Project

Let’s create a React app to build our Task Tracker using ES6 features.

1. Create a New React App:

Open your terminal and run:

npx create-react-app task-tracker
cd task-tracker

2. Start the Development Server:

Run:

npm start

This opens your app at http://localhost:3000.

3. Clean Up:

Open src/App.js and replace its content with:

const App = () => {
  return (
    <div>
      <h1>Task Tracker</h1>
    </div>
  );
};

export default App;

Delete src/App.css, src/logo.svg, and update src/index.css with:

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 20px;
  background-color: #f5f5f5;
}

Building the Task Tracker App

Our Task Tracker app will:

  • Display a list of tasks.
  • Allow users to add new tasks via a form.
  • Use ES6 features like arrow functions, destructuring, modules, and template literals.

Step 1: Create the Task Component

In src, create a file named Task.js:

const Task = ({ title, completed }) => {
  return (
    <div style={{
      padding: '10px',
      backgroundColor: completed ? '#e0e0e0' : '#fff',
      margin: '5px 0',
      borderRadius: '4px',
      boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
    }}>
      <p>{`Task: ${title}`}</p>
    </div>
  );
};

export default Task;

Step 2: Create the TaskForm Component

In src, create a file named TaskForm.js:

const TaskForm = ({ onAddTask }) => {
  const [title, setTitle] = React.useState('');
  
  const handleSubmit = (e) => {
    e.preventDefault();
    if (title.trim()) {
      onAddTask({ title, completed: false });
      setTitle('');
    }
  };

  return (
    <form onSubmit={handleSubmit} style={{ marginBottom: '20px' }}>
      <input 
        type="text" 
        value={title} 
        onChange={(e) => setTitle(e.target.value)} 
        placeholder="Enter a new task" 
        style={{
          padding: '8px', 
          marginRight: '10px', 
          borderRadius: '4px'
        }} 
      />
      <button 
        type="submit" 
        style={{
          padding: '8px 16px', 
          backgroundColor: '#007bff', 
          color: '#fff', 
          border: 'none', 
          borderRadius: '4px'
        }}
      >
        Add Task
      </button>
    </form>
  );
};

export default TaskForm;

Step 3: Update the App Component

Update src/App.js to manage tasks and render the components:

import Task from './Task';
import TaskForm from './TaskForm';

const App = () => {
  const [tasks, setTasks] = React.useState([
    { title: 'Learn React', completed: false },
    { title: 'Practice ES6', completed: true }
  ]);

  const addTask = (newTask) => {
    setTasks([...tasks, newTask]);
  };

  return (
    <div>
      <h1>Task Tracker</h1>
      <TaskForm onAddTask={addTask} />
      <div>
        {tasks.map((task, index) => (
          <Task key={index} {...task} />
        ))}
      </div>
    </div>
  );
};

export default App;

Step 4: Test the App

  • Save all files and ensure the development server is running (npm start).
  • Open http://localhost:3000. You should see:
    • A form to add tasks.
    • Two initial tasks (“Learn React” and “Practice ES6”).
    • The ability to add new tasks, which will appear in the list.

Understanding the Code

Let’s recap how ES6 enhances our React app:

  • Arrow Functions: Used in Task, TaskForm, and App for concise syntax and proper this binding in event handlers.
  • Destructuring: Simplified prop access in Task and TaskForm (e.g., { title, completed }).
  • Modules: Organized code by splitting Task and TaskForm into separate files, imported into App.
  • Template Literals: Added dynamic text in Task (Task: ${title}).
  • Spread Operator: Passed props efficiently (<Task {...task} />) and updated state ([...tasks, newTask]).

Common ES6 Pitfalls in React

  • Arrow Functions in Render: Avoid defining arrow functions inline in JSX (e.g., onClick={() => doSomething()}) for performance reasons. Define them outside the render: const handleClick = () => doSomething(); return <button onClick={handleClick}>Click</button>;
  • Destructuring Errors: Ensure props exist before destructuring, or use default parameters: const Task = ({ title = 'Untitled' }) => <p>{title}</p>;
  • Module Imports: Use named imports correctly (e.g., import { Task } from './Task' if not default).

What’s Next?

You’ve built a Task Tracker app using ES6 with React! Here are some ways to continue learning:

  • More ES6 Features: Explore Promises, async/await, or Array.map for advanced React patterns.
  • State Management: Add a feature to toggle task completion using useState.
  • Styling: Use a CSS-in-JS library like Emotion or a framework like Tailwind CSS.
  • Build Another App: Create a shopping list or note-taking app to practice ES6.

Practice Challenge

Add a button to each Task component to mark it as completed. Use an arrow function for the event handler and the spread operator to update the tasks array in App.


Resources


Congratulations on mastering ES6 with React! You’re now ready to write modern, clean React code. Keep practicing and happy coding!