Getting Started with ReactJs

React is a JavaScript library for building user interfaces. This guide will help you set up your first React application and understand the fundamental concepts needed to start building interactive web applications.

Prerequisites

Before starting with React, ensure you have:

  • Node.js (version 18 or higher) - Download from nodejs.org
  • A code editor - VS Code, WebStorm, or your preferred editor
  • Basic JavaScript knowledge - Understanding of functions, arrays, objects, and ES6 syntax
  • Terminal/Command line - Basic familiarity with command-line tools

Verify your Node.js installation:

node --version
npm --version

Creating Your First React App

The fastest way to create a React application is using Vite, a modern build tool that provides a fast development experience:

npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev

This creates a new React project with:

  • Development server with hot module replacement
  • Optimized production build configuration
  • Modern JavaScript and JSX support out of the box

Your application will be running at http://localhost:5173

Alternative: Create React App

While Vite is recommended, Create React App remains a popular option:

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

Project Structure

After creating your project, you’ll see this structure:

my-react-app/
├── node_modules/       # Dependencies
├── public/             # Static assets
│   └── favicon.ico
├── src/                # Source code
│   ├── App.jsx         # Main App component
│   ├── App.css         # App styles
│   ├── main.jsx        # Entry point
│   └── index.css       # Global styles
├── index.html          # HTML template
├── package.json        # Project configuration
└── vite.config.js      # Vite configuration

Your First Component

Open src/App.jsx and replace its contents with:

function App() {
  return (
    <div className="App">
      <h1>Hello, React!</h1>
      <p>Welcome to your first React application.</p>
    </div>
  );
}

export default App;

This is a function component, the modern way to write React components. It:

  • Is a JavaScript function that returns JSX
  • Can accept props as arguments
  • Can use Hooks for state and side effects

Understanding JSX

JSX looks like HTML but is actually JavaScript. Key differences:

function Welcome() {
  const name = "World";
  const isLoggedIn = true;
  
  return (
    <div className="welcome">
      {/* JavaScript expressions in curly braces */}
      <h1>Hello, {name}!</h1>
      
      {/* Conditional rendering */}
      {isLoggedIn ? (
        <p>Welcome back!</p>
      ) : (
        <p>Please sign in.</p>
      )}
      
      {/* Inline styles use objects */}
      <p style=>
        Styled text
      </p>
    </div>
  );
}

Important JSX rules:

  • Use className instead of class
  • All tags must be closed (<img />, <br />)
  • Use camelCase for attributes (onClick, onChange)
  • Wrap JavaScript expressions in curly braces

Adding State with useState

State allows components to remember and react to user input:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

The useState Hook:

  • Takes initial state as an argument
  • Returns an array with current state and setter function
  • Triggers re-render when state changes

Handling Events

React events use camelCase and pass functions as handlers:

function Form() {
  const [text, setText] = useState('');
  
  const handleChange = (event) => {
    setText(event.target.value);
  };
  
  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`You entered: ${text}`);
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text"
        value={text}
        onChange={handleChange}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Rendering Lists

Use JavaScript’s map function to render lists:

function TodoList() {
  const todos = [
    { id: 1, text: 'Learn React' },
    { id: 2, text: 'Build an app' },
    { id: 3, text: 'Deploy to production' }
  ];
  
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

Always include a unique key prop when rendering lists. Keys help React identify which items have changed, been added, or removed.

Component Composition

Break your UI into smaller, reusable components:

function WelcomeMessage({ name }) {
  return <h1>Hello, {name}!</h1>;
}

function UserProfile({ user }) {
  return (
    <div className="profile">
      <WelcomeMessage name={user.name} />
      <p>Email: {user.email}</p>
      <p>Role: {user.role}</p>
    </div>
  );
}

function App() {
  const user = {
    name: 'Alice',
    email: 'alice@example.com',
    role: 'Developer'
  };
  
  return <UserProfile user={user} />;
}

Practical Example: Todo App

Here’s a complete example combining these concepts:

import { useState } from 'react';

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');
  
  const addTodo = () => {
    if (input.trim()) {
      setTodos([...todos, {
        id: Date.now(),
        text: input,
        completed: false
      }]);
      setInput('');
    }
  };
  
  const toggleTodo = (id) => {
    setTodos(todos.map(todo =>
      todo.id === id
        ? { ...todo, completed: !todo.completed }
        : todo
    ));
  };
  
  const deleteTodo = (id) => {
    setTodos(todos.filter(todo => todo.id !== id));
  };
  
  return (
    <div className="todo-app">
      <h1>My Todos</h1>
      
      <div className="input-section">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && addTodo()}
          placeholder="Add a new todo"
        />
        <button onClick={addTodo}>Add</button>
      </div>
      
      <ul className="todo-list">
        {todos.map(todo => (
          <li key={todo.id} className={todo.completed ? 'completed' : ''}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => toggleTodo(todo.id)}
            />
            <span>{todo.text}</span>
            <button onClick={() => deleteTodo(todo.id)}>Delete</button>
          </li>
        ))}
      </ul>
      
      <p>{todos.filter(t => !t.completed).length} items remaining</p>
    </div>
  );
}

export default TodoApp;

Next Steps

Now that you understand the basics, continue learning:

  1. Components - Deep dive into component patterns
  2. Hooks - Learn useEffect, useContext, and custom Hooks
  3. JSX - Master JSX syntax and patterns
  4. State Management - Handle complex state with Context API

Common Beginner Mistakes

1. Mutating State Directly

Never directly modify state values. Always create new objects or arrays when updating state.

// Wrong - mutating state directly
const handleClick = () => {
  items.push(newItem);
  setItems(items);
};

// Correct - create new array
const handleClick = () => {
  setItems([...items, newItem]);
};

Reference: State as a Snapshot - Official React documentation on why mutating state directly doesn’t work.

2. Forgetting Keys in Lists

Always provide a unique key prop when rendering lists. Keys help React identify which items have changed.

// Wrong - no key prop
{items.map(item => <li>{item.name}</li>)}

// Correct - unique key
{items.map(item => <li key={item.id}>{item.name}</li>)}

Reference: Keeping list items in order with key - Learn why keys are essential for list rendering.

3. Using Index as Key

Using array indices as keys causes problems when lists are reordered, filtered, or have items added/removed.

// Avoid - index as key causes issues with reordering
{items.map((item, index) => <li key={index}>{item.name}</li>)}

// Better - use unique identifier
{items.map(item => <li key={item.id}>{item.name}</li>)}

Reference: Rules of Keys - Official documentation explaining why using indices as keys is problematic.

4. Calling Handlers Instead of Passing Them

Pass function references to event handlers, don’t call them immediately. Use arrow functions if you need to pass arguments.

// Wrong - calls function immediately
<button onClick={handleClick()}>Click</button>

// Correct - passes function reference
<button onClick={handleClick}>Click</button>

// Correct - arrow function for parameters
<button onClick={() => handleClick(id)}>Click</button>

Reference: Responding to Events - Learn the correct patterns for passing event handlers.

Development Tools

React Developer Tools

Install the React DevTools browser extension for Chrome or Firefox. It allows you to:

  • Inspect component hierarchies
  • View and edit props and state
  • Profile component performance
  • Debug React applications effectively

ESLint and Prettier

Set up linting and formatting for consistent code:

npm install --save-dev eslint prettier eslint-config-prettier

Configure ESLint in .eslintrc.json:

{
  "extends": [
    "react-app",
    "prettier"
  ]
}

Resources

Practice Projects

Build these projects to solidify your understanding:

  1. Recipe Book - Create, read, update, and delete recipes
  2. Expense Tracker - Track income and expenses with charts
  3. Quiz App - Create an interactive quiz with scoring

Start with simple projects and gradually increase complexity as you become more comfortable with React’s concepts and patterns.