Structure of a Basic React App: Files, Components, Functions, Classes & Props




📦 Basic React App Structure

├── node_modules/ # All 3rd-party dependencies
├── public/ # Static assets
│ ├── index.html # Main HTML template
│ ├── favicon.ico # Browser tab icon
│ └── manifest.json # PWA configuration
├── src/ # Core application
│ ├── App.js # Root component
│ ├── index.js # JavaScript entry point
│ └── *.css # Component styles
├── package.json # Dependencies & scripts
└── README.md # Project docs

How They Work Together

  1. Entry Point: public/index.html loads src/index.js, which renders your App component
  2. Component Tree: App.js acts as the root that composes other components
  3. Dependencies: package.json defines all required packages
  4. Build Process: Tools bundle src/ into optimized production files
💡 Pro Tip: The src/index.js is where React's virtual DOM connects to the actual DOM via ReactDOM.render().

⚛️ Creating a New React Component

Step 1: Create Component File

src/
├── Component1.js # New component file (use command rfc in vscode to generate a reactFunctionalComponent)
// Basic component template:
import React from 'react';

function Component1() {
return (
<div>
<!-- Your JSX here -->
</div>
);
}

export default Component1;

Step 2: Import in App.js

import Component1 from './Component1';
// Add to your component tree:
<Component1 />
💡 Key Concepts:
  • Component files use PascalCase naming
  • Always include the export statement
  • Self-closing tag syntax (<Component1 />) is preferred when no children are needed

⚡ Passing Props in React

Component Definition (Component1.js)

import React from 'react'

export default function Component1(props) {
return (
<div>
This is our first component with the name <b>{props.name}</b>.
</div>
)
}

Component Usage (App.js)

<Component1 name="John" />
// Renders: "This is our first component with the name John."

How Props Work

  • Data Flow: Parent (App.js) → Child (Component1.js)
  • Immutable: Components cannot modify their props
  • Dynamic: Can pass variables like name={userName}
  • Type Safety: Consider using PropTypes or TypeScript

🚗 React Class Component with Props

Class Component Definition (Car.js)

import React from "react";

export class Car extends React.Component {
constructor(props) {
super(props);
}

render() {
return (
<h2>
Car component with color <b style={{color:this.props.color}}>
{this.props.color}
</b>
</h2>
)
}
}

Component Usage (App.js)

<Car color="orange" />
// Renders:

Car component with color orange

Key Elements Explained

  • Class Declaration: class Car extends React.Component creates a class component
  • Constructor: Receives and passes props to parent class via super(props)
  • Props Access: Accessed via this.props.color throughout the component
  • Dynamic Styling: Inline style uses the prop value: style={{color:this.props.color}}
  • Render Method: Required method that returns JSX to display
💡 Note: While class components are still supported, modern React primarily uses function components with hooks.

See also this to learn how I learned how to pass the prop variable inside the html color tag.



- Dave

Understanding State Variables in ReactJS

In this tutorial, we'll explore how to implement and use state variables in React functional components using the useState hook.

Implementation Overview

I created a component called Component1 that accepts props and maintains its own state. Here's the key implementation:

import {React, useState} from 'react'

export default function Component1(props) {
  // Initialize state variable 'time' with initial value of 0
  const [time, setTime] = useState(0)

  // Function to update the state when button is clicked
  const handleClick = () => {
    setTime(time => time + 1)
  }

  return (
    <div>
      This is our first component with the name <b>{props.name}</b>.
      <h1>The number is {props.number}</h1>
      <h2>The time is {time}</h2>
      <button onClick={handleClick}>Click me!</button>
    </div>
  )
}

Key Elements Explained

1. useState Hook

The useState hook is a fundamental React hook that allows functional components to manage state. It returns an array with two elements: the current state value and a function to update that state.

2. State Variable (time)

The time variable holds the current value of our state. It's initialized to 0 and will persist between component re-renders.

3. Setter Function (setTime)

The setTime function is used to update the value of time. When called, it triggers a re-render of the component with the new state value.

4. handleClick Function

This is our event handler that gets called when the button is clicked. It uses the functional update form of setTime to increment the previous state value by 1.

5. Button with onClick Handler

The button element has an onClick attribute that points to our handleClick function, creating the connection between user interaction and state update.

Usage in App.js

// In App.js
<Component1 name="John" number={3}/>

This passes two props to Component1: a string "John" for the name prop and the number 3 for the number prop.

Live Demo

This is our first component with the name John.

The number is 3

The time is 0

Implementing React Router in Your Application

Updated App.js Structure

Added necessary imports and routing structure:

App.js
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
import Home from './Components/Home';
import About from './Components/About';
import Contact from './Components/Contact';

function App() {
  return (
    <Router>
      <div className="App">
        <h1>Hello World!</h1>
        
        {/* Navigation Links */}
        <nav>
          <Link to='/home'>Home</Link>
          <Link to='/about'>About</Link>
          <Link to='/contact'>Contact</Link>
        </nav>
        
        <Component1 name="John" number={3}/>
        <Car color="orange"/>
        <br/>
        
        {/* Route Definitions */}
        <Routes>
          <Route path='/home' element={<Home/>}/>
          <Route path='/about' element={<About/>}/>
          <Route path='/contact' element={<Contact/>}/>
        </Routes>
      </div>
    </Router>
  );
}

export default App;

Component Files Created

Added three components in the Components folder:

Components/Home.js
import React from 'react'

function Home() {
  return (
    <div>Home</div>
  )
}

export default Home
Components/About.js
import React from 'react'

function About() {
  return (
    <div>About</div>
  )
}

export default About
Components/Contact.js
import React from 'react'

function Contact() {
  return (
    <div>Contact</div>
  )
}

export default Contact

Summary of Changes

  • Installed and imported React Router DOM
  • Wrapped the application with the Router component
  • Defined routes for Home, About, and Contact components
  • Created navigation using Link components
  • Generated basic component templates using VS Code's 'rfce' command

Array Mapping in React.js with Bootstrap Styling

This tutorial demonstrates how to map through arrays in React and display the data in a styled Bootstrap table. Perfect for displaying user data, product listings, or any tabular data from an array.

Implementation Steps:

1. Install Bootstrap
npm install bootstrap
2. Import Bootstrap CSS

Add this to your index.js file:

import 'bootstrap/dist/css/bootstrap.min.css';
3. Create User Data Array with useState
const [users, setUsers] = useState([
  {'firstName': 'John', 'lastName': 'Doe'},
  {'firstName': 'Jane', 'lastName': 'Plain'}
])
4. Install React Bootstrap
npm install react-bootstrap
5. Import Table Component
import Table from 'react-bootstrap/Table';

Live Demo Result:

First Name Last Name
John Doe
Jane Plain

Final React Component Code:

import React, { useState } from 'react';
import Table from 'react-bootstrap/Table';

function UserTable() {
  // State hook to store our array of users
  const [users, setUsers] = useState([
    {'firstName': 'John', 'lastName': 'Doe'},
    {'firstName': 'Jane', 'lastName': 'Plain'}
  ]);

  return (
    <div>
      <h1>Users</h1>
      
      <Table striped bordered hover variant="dark">
        <thead>
          <tr>
            <th>First Name</th>
            <th>Last Name</th>
          </tr>
        </thead>
        <tbody>
          {/* Map through users array and render a table row for each user */}
          {users.map((user, index) => {
            return (
              <tr key={index}>
                <td>{user.firstName}</td>
                <td>{user.lastName}</td>
              </tr>
            )
          })}
        </tbody>
      </Table>
    </div>
  );
}

export default UserTable;

Key Takeaways:

  • Array mapping is essential for rendering lists in React
  • Always add a unique key prop when mapping elements
  • Bootstrap provides pre-styled components that work well with React
  • The combination of React and Bootstrap allows for clean, maintainable UI code

Comments