📦 Basic React App Structure
How They Work Together
- Entry Point:
public/index.htmlloadssrc/index.js, which renders yourAppcomponent - Component Tree:
App.jsacts as the root that composes other components - Dependencies:
package.jsondefines all required packages - Build Process: Tools bundle
src/into optimized production files
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
Step 2: Import in App.js
- Component files use
PascalCasenaming - Always include the
exportstatement - Self-closing tag syntax (
<Component1 />) is preferred when no children are needed
⚡ Passing Props in React
Component Definition (Component1.js)
Component Usage (App.js)
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)
Component Usage (App.js)
Car component with color orange
Key Elements Explained
- Class Declaration:
class Car extends React.Componentcreates a class component - Constructor: Receives and passes
propsto parent class viasuper(props) - Props Access: Accessed via
this.props.colorthroughout the component - Dynamic Styling: Inline style uses the prop value:
style={{color:this.props.color}} - Render Method: Required method that returns JSX to display
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:
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:
import React from 'react'
function Home() {
return (
<div>Home</div>
)
}
export default Home
import React from 'react'
function About() {
return (
<div>About</div>
)
}
export default About
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
Post a Comment