React Toutrial 1

Step 1: Create a React App using Vite

Vite is a fast and modern build tool that helps in creating React apps with minimal configuration. To create a React app with Vite:

Open your VS code and then open your terminal and run:

npm create vite@latest my-app -- --template react

A new folder will be created with the name “my-app”. Open that folder in VS code:

Open the terminal again and install dependencies and start the development server:

npm install

Step 2: Alternative: Create a React App using Stackblitz or Replit

Alternatively, you can use online coding platforms like Stackblitz or Replit if you don’t want to set up a local environment.

  • Stackblitz: Go to Stackblitz and create a new React project. Stackblitz handles all configurations automatically.
  • Replit: Similarly, you can create a new React project on Replit, which is another code-hosting platform.

These platforms are good for quick prototyping without needing to install anything locally.

Step 3: Clean the following files

Once your app is set up, clean up the unnecessary code from the following files:

  • App.jsx: Remove any default code that Vite or React provides.
  • App.css: Clear out any unnecessary styles to start with a blank slate.
  • Index.css: This file contains global styles. You can clear it or adjust as needed for your project.

This will give you a clean starting point to build your application.

Step 4: Add React Bootstrap library

React Bootstrap is a popular front-end framework that provides ready-made components. To install it, run in the terminal window:

npm install react-bootstrap bootstrap

Next, import Bootstrap’s CSS into your app by adding this line at the top of your main.jsx or index.jsx file:

import 'bootstrap/dist/css/bootstrap.min.css';

This will enable Bootstrap styles in your React app.

Step 5: Add a Navbar to Your Page

Using React Bootstrap, create a Navbar component in a file called mynavbar.jsx:

import { Navbar, Nav } from 'react-bootstrap';

const MyNavbar = () => {
  return (
    <Navbar bg="light" expand="lg">
      <Navbar.Brand href="/">My App</Navbar.Brand>
      <Navbar.Toggle aria-controls="basic-navbar-nav" />
      <Navbar.Collapse id="basic-navbar-nav">
        <Nav className="mr-auto">
          <Nav.Link href="/">Home</Nav.Link>
          <Nav.Link href="/allcourses">All Courses</Nav.Link>
          <Nav.Link href="/mycourses">My Courses</Nav.Link>
          <Nav.Link href="/coursedetail/C3KGU1">UI Design Course</Nav.Link>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  );
};

export default MyNavbar;

The navbar should have links for Home, All Courses, My Courses, and UI Design Course.

Step 6: Add Multiple Components and Render Them Below the Navbar

Create several components, each with a simple “Hello” message:

1.myhome.jsx:

const MyHome = () => <h1>Hello from My Home</h1>;
export default MyHome;

2. courses.jsx:

const Courses = () => <h1>Hello from Courses</h1>;
export default Courses;

3.coursedetail.jsx:

const CourseDetail = () => <h1>Hello from Course Detail</h1>;
export default CourseDetail;

In App.jsx, import and render these components below the Navbar.

the code in App.jsx should look like this:

import MyNavbar from './mynavbar';
import MyHome from './myhome';
import Courses from './courses';
import CourseDetail from './coursedetail';

function App() {
  return (
<> 
  <MyNavbar></MyNavbar>
  <MyHome></MyHome>
  <Courses></Courses>
  <CourseDetail></CourseDetail>
</>
  );
}

export default App;

Now run the app using

npm run dev

Step 7: Add React Router to Your App

React Router allows you to create multiple routes in your app. Install it by running:

npm install react-router-dom

Then, update your App.jsx file to set up routing:

import { BrowserRouter, Route, Routes } from 'react-router-dom';
import MyNavbar from './mynavbar';
import MyHome from './myhome';
import Courses from './courses';
import CourseDetail from './coursedetail';

function App() {
  return (
    <BrowserRouter>
      <MyNavbar />
      <Routes>
        <Route path="/" element={<MyHome />} />
        <Route path="/allcourses" element={<Courses />} />
        <Route path="/mycourses" element={<Courses />} />
        <Route path="/coursedetail" element={<CourseDetail />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

This setup ensures that when you click on links in the Navbar, the respective component gets displayed.

Step 8: Fetch Data Using JSON in App.jsx

Create a data.json file to simulate course data. For example:

[
{
    "id": 1,
    "name": "React Basics",
    "description": "Learn the basics of React."
  },
  {
    "id": 2,
    "name": "UI Design",
    "description": "Learn the principles of UI design."
  }
]

 

You can find the sample JSON file here:

Then, change App.jsx, as following:

First add this import:

import { useState, useEffect } from 'react';

and then add following lines to the App function for fetching data. Create a folder “data” in public folder and copy the “course.json” to “public/data” folder.

function App() {

const [myData, setMyData] = useState([]);

useEffect(() => {
  fetch('/data/courses.json')
    .then(response => response.json()) //return a Java script object Promise. If you are expecting a text, use the response.text()
    .then(result => {
      setMyData(result);
    })
    .catch(error => console.error('Error fetching data:', error));
}, []);  // using empty dependency [] ensures the fetch only occurs once when the components renders

  return (
    myData&&
    // Same as before
  );
}

 

Step 9: Send Data to Components

Pass the fetched course data to the Courses and CourseDetail components as props. Complete the following routes in the code:

      <Routes>
        <Route path="/" element={<MyHome />} />
        <Route path="/allcourses" element={<Courses myparam={"allcourses"} coursedata={myData} />} />
        <Route path="/mycourses" element={<Courses myparam={"mycourses"} coursedata={myData} />} />
        <Route path="/coursedetail">
          <Route path=":courseId" element={<CourseDetail coursedata={myData} />} />
        </Route>
      </Routes>

Step 10: Add Tailwind to the App

Tailwind CSS is a utility-first CSS framework. Install Tailwind by running:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Next, configure Tailwind by adding the following to your tailwind.config.js:

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ], theme: {
    extend: {},
  },
  plugins: [],
}

Finally, import Tailwind into your index.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

Step 11: Add a Tailwind card to display list of courses

Now that Tailwind is set up, use its card styles to display the course list:


import { useNavigate } from "react-router-dom";
function Courses(props) {

  let navigate = useNavigate(); // this is used to navigate when clicking on view details button.

  let courses = props.coursedata.courses;
  if (courses && props.myparam == "mycourses") courses = courses.filter(p=>p.mycourse == 1)//here the mycouse property in the object is checked for findig "mycourse".
    return (
     courses && <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
        {courses.map(course => (
          <div key={course.id} className="bg-white shadow-md rounded-lg overflow-hidden border-2">
            {/* Course Image */}
            <img 
              src={course.image} 
              alt={course.name} 
              className="w-full h-48 object-contain" 
            />
            
            {/* Course Details */}
            <div className="p-6">
              <h2 className="text-xl font-bold mb-2">{course.name}</h2>
              <p className="text-gray-600 text-sm mb-2">
                <span className="font-semibold">Course Code:</span> {course.code}
              </p>
  
              {/* Truncated Course Description */}
              <p className="text-gray-600 mb-4">
                {course.desc.substring(0,200) + "..."}
              </p>
  
              <div className="text-gray-700 mb-2">
                <span className="font-semibold">Credits:</span> {course.credit}
              </div>
              <div className="text-gray-700">
                <span className="font-semibold">Year:</span> {course.year}
              </div>
            </div>
  
            {/* View Details Button */}
            <div className="bg-gray-100 p-4">
              <button onClick={()=>navigate("/coursedetail/" + course.code)} className="bg-blue-500 text-white font-semibold px-4 py-2 rounded hover:bg-blue-600">
                View Details
              </button>
            </div>
          </div>
        ))}
      </div>
    );
  };
  
  export default Courses;

Step 12: Show Course Details Using useParams

For dynamic course details, use useParams from React Router. Update the CourseDetail component to fetch course details by ID:

import { useParams } from "react-router-dom";

function CourseDetail(props) {

let { courseId } = useParams  ();

const course =  props.coursedata.courses && props.coursedata.courses.find(p=>p.code == courseId) 

if (!course) return <h1 className="text-center text-red-500 text-xl font-bold">Course not found</h1>;

  return (
    <div className="flex justify-center mt-10">
      <div className="max-w-3xl bg-white shadow-lg rounded-lg overflow-hidden">
        <div className="bg-blue-500 p-6">
          <h1 className="text-white text-4xl font-bold">{course.name}</h1>
        </div>
        <div className="p-6">
          <h2 className="text-2xl font-semibold mb-4">Course Description</h2>
          <p className="text-gray-700 text-lg leading-relaxed">{course.desc}</p>
        </div>
        <div className="bg-gray-100 p-6">
          <h3 className="text-xl font-medium mb-2">Course Details</h3>
          <ul className="list-disc list-inside text-gray-700">
            <li><span className="font-semibold">Code: </span>{course.code}</li>
            <li><span className="font-semibold">Name: </span>{course.name}</li>
            <li><span className="font-semibold">Year:</span>{course.year}</li>
          </ul>
        </div>
      </div>
    </div>
  );
};
export default CourseDetail;

Now, clicking on a course will take you to its details page.

Scroll to Top