0% found this document useful (0 votes)
4 views

React JS Experiment

The document outlines a series of practical experiments designed to teach React.js concepts, including creating components, using JSX, managing state, and implementing routing. Each experiment has specific aims, objectives, and code implementations to demonstrate key features of React, such as props, controlled components, and nested routing. The document serves as a comprehensive guide for learners to build and understand various aspects of React applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

React JS Experiment

The document outlines a series of practical experiments designed to teach React.js concepts, including creating components, using JSX, managing state, and implementing routing. Each experiment has specific aims, objectives, and code implementations to demonstrate key features of React, such as props, controlled components, and nested routing. The document serves as a comprehensive guide for learners to build and understand various aspects of React applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Practical Experiment on React.

js
Sr. No. Experiment Name List
To create a simple React.js application that displays a
1 welcome message using JSX and demonstrates React
component-based architecture.
To compare JavaScript and JSX by creating UI elements
2
using both approaches in a React app.
To demonstrate how to pass data (props) to a React
3
functional component using JSX.
To create a functional React component and apply CSS
4
styling to it.
To demonstrate the use of state in a React functional
5
component by creating a counter application.
To pass dynamic data from a parent component to a child
6
component using props and validate it using PropTypes.
To create a controlled component in React where the input
7
field is controlled using the state.
To implement basic routing in a React application using
8
BrowserRouter.
To implement nested routes, allowing sub-pages within a
9
main page.
10 To restrict access to a route unless the user is authenticated.
Experiment 1: Creating a Simple React Component with
JSX
Aim: To create a simple React.js application that displays a welcome message using JSX and demonstrates
React component-based architecture.

Objective:

1. Learn how to write JSX in a React component.


2. Understand how React components render UI elements.
3. Set up a basic React app and display JSX-based content.

Theory:

 React.js is a JavaScript library used for building user interfaces.


 JSX (JavaScript XML) is a syntax extension that allows writing HTML-like elements inside
JavaScript.
 A React component is a reusable block of code that defines UI elements.

Code Implementation:

Step 1: Install and Set Up React

1. Install Node.js from Node.js Official Website.


2. Open a terminal and run the following command to create a React app:

npx create-react-app experiment1


cd experiment1
npm start

Step 2: Modify App.js to Include JSX Code

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

import React from "react";

function Greeting() {
return <h1>Hello, Welcome to React with JSX!</h1>;
}

function App() {
return (
<div>
<Greeting />
<p>This is a JSX-based React component.</p>
</div>
);
}

export default App;

Step 3: Execute the Code

1. Save the file and go back to the terminal.


2. Run the app:

npm start

3. Open http://localhost:3000/ in a browser to see the output:

Hello, Welcome to React with JSX!


This is a JSX-based React component.

Results:

 Successfully created and rendered a React component using JSX.


 Learned how JSX allows writing HTML-like syntax in React.
Experiment 2: Understanding the Difference Between
JavaScript and JSX
Aim: To compare JavaScript and JSX by creating UI elements using both approaches in a React app.

Objective:

1. Understand how React components work with JavaScript and JSX.


2. Learn the advantages of JSX over traditional JavaScript.
3. Compare JSX-based rendering with React.createElement().

Theory:

 In JavaScript, UI elements are created using document.createElement() or


React.createElement().
 JSX provides a cleaner and more readable way to define UI elements.

Code Implementation:

Step 1: Modify App.js to Compare JavaScript and JSX

Replace the content of src/App.js with the following code:

import React from "react";

// Creating an element using JavaScript


const jsElement = React.createElement(
"h1",
{ className: "title" },
"This is created using JavaScript!"
);

// Creating an element using JSX


const jsxElement = <h1 className="title">This is created using
JSX!</h1>;

function App() {
return (
<div>
{jsElement}
{jsxElement}
</div>
);
}

export default App;


Step 2: Execute the Code

1. Save the file and run:

npm start

2. Open http://localhost:3000/ to see the output:

This is created using JavaScript!


This is created using JSX!

Results:

 Successfully demonstrated how React elements are created using both JavaScript and JSX.
 JSX provides a cleaner and more readable way to define UI elements.
Experiment 3: Creating a Functional Component with Props in JSX
Aim: To demonstrate how to pass data (props) to a React functional component using JSX.

Objective:

1. Learn how to pass and use props in a React component.


2. Understand how JSX allows dynamic content rendering.
3. Display personalized messages using props.

Theory:

 Props (Properties) allow components to receive data and render dynamic content.
 JSX expressions can embed JavaScript inside curly braces {}.

Code Implementation:

Step 1: Modify App.js to Use Props

Replace the content of src/App.js with:

import React from "react";

function Welcome(props) {
return <h1>Welcome, {props.name}!</h1>;
}

function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
<Welcome name="Charlie" />
</div>
);
}

export default App;

Step 2: Execute the Code

1. Save the file and run:

npm start

2. Open http://localhost:3000/ to see the output:

Welcome, Alice!
Welcome, Bob!
Welcome, Charlie!

Results:

 Successfully used props to pass dynamic values to a React component.


 Demonstrated how JSX allows rendering dynamic content.
Experiment 4: Creating and Styling a Functional Component
Aim: To create a functional React component and apply CSS styling to it.

Objective:

1. Understand how to create a React functional component.


2. Learn how to apply CSS styling to a component.
3. Render the component inside the main App.js file.

Theory:

 A functional component is a simple JavaScript function that returns JSX.


 Styling in React can be done using CSS classes, inline styles, or styled-components.

Code Implementation:

Step 1: Install and Set Up React

1. Open the terminal and create a React app:


2. npx create-react-app experiment1
3. cd experiment1
4. npm start

Step 2: Create a New Component (Greeting.js)

Inside the src folder, create a new file Greeting.js and add the following code:

import React from "react";


import "./Greeting.css"; // Import the CSS file

function Greeting() {
return <h1 className="greeting-text">Hello, Welcome to React!</h1>;
}

export default Greeting;

Step 3: Add Styling (Greeting.css)

Create a new file Greeting.css in the src folder and add:

.greeting-text {
color: blue;
font-size: 24px;
text-align: center;
margin-top: 20px;
}

Step 4: Use the Component in App.js

Modify src/App.js to include the Greeting component:

import React from "react";


import Greeting from "./Greeting";
function App() {
return (
<div>
<Greeting />
</div>
);
}

export default App;

Step 5: Execute the Code

1. Save all files.


2. Run the React app:
3. npm start
4. Open http://localhost:3000/ in a browser.

Result:

 Successfully created and rendered a functional component.


 Applied CSS styling to the component.
Experiment 5: Using State in a Component
Aim: To demonstrate the use of state in a React functional component by creating a counter application.

Objective:

1. Learn how to declare state in a functional component using useState().


2. Understand how state updates cause re-rendering.
3. Create a button-based counter where clicking increases the count.

Theory:

 State allows a component to manage dynamic data.


 useState(initialValue) is a React Hook used to create and update state.

Code Implementation:

Step 1: Modify App.js to Include State-Based Counter

Replace the content of src/App.js with:

import React, { useState } from "react";

function Counter() {
// Declare state
const [count, setCount] = useState(0);

return (
<div style={{ textAlign: "center", marginTop: "20px" }}>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
<button onClick={() => setCount(count - 1)}>Decrease</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}

function App() {
return <Counter />;
}

export default App;

Step 2: Execute the Code

1. Save all files.


2. Run the React app:
3. npm start
4. Open http://localhost:3000/ in a browser.

Result:

 Successfully implemented state in a React component.


 Clicking the buttons increases, decreases, and resets the counter.
Experiment 6: Passing Data Using Props and Validating with
PropTypes
Aim: To pass dynamic data from a parent component to a child component using props and validate it
using PropTypes.

Objective:

1. Understand how to pass data using props in React.


2. Use PropTypes to ensure correct data types.
3. Set default values for props using defaultProps.

Theory:

 Props (Properties) allow data to be passed from parent to child components.


 PropTypes is a package that helps validate props for better debugging.
 defaultProps assigns default values when no props are provided.

Code Implementation:

Step 1: Install PropTypes

In the terminal, install the prop-types package:

npm install prop-types

Step 2: Create a New Component (User.js)

Inside the src folder, create a file User.js and add:

import React from "react";


import PropTypes from "prop-types";

function User({ name, age }) {


return (
<div>
<h1>Name: {name}</h1>
<h2>Age: {age}</h2>
</div>
);
}

// Validate Props
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};

// Default Props
User.defaultProps = {
name: "Guest",
age: 18,
};
export default User;

Step 3: Use the Component in App.js

Modify src/App.js to pass data dynamically:

import React from "react";


import User from "./User";

function App() {
return (
<div>
<User name="Alice" age={25} />
<User name="Bob" age={30} />
<User /> {/* Uses default props */}
</div>
);
}

export default App;

Step 4: Execute the Code

1. Save all files.


2. Run the React app:
3. npm start
4. Open http://localhost:3000/ in a browser.

Result:

 Successfully passed dynamic data using props.


 Validated data types with PropTypes.
 Used default props when no data was provided.
Experiment 7: Handling Form Inputs Using Controlled
Components
Aim: To create a controlled component in React where the input field is controlled using the state.

Objective:

1. Understand controlled components in React.


2. Learn how to manage form inputs using useState().
3. Implement an input field where the user enters their name, and it is dynamically displayed.

Theory:

 In a controlled component, form inputs are controlled by React state, not by the DOM.
 The value of the input is tied to the state, and onChange updates the state.
 Controlled components allow better control over user inputs.

Code Implementation:

Step 1: Modify App.js to Include a Controlled Form

Replace the content of src/App.js with the following code:

jsx
CopyEdit
import React, { useState } from "react";

function NameForm() {
// Declare state to store input value
const [name, setName] = useState("");

return (
<div style={{ textAlign: "center", marginTop: "20px" }}>
<h1>Controlled Component Example</h1>
<input
type="text"
placeholder="Enter your name"
value={name} // Controlled by state
onChange={(e) => setName(e.target.value)} // Updates state
style={{ padding: "10px", fontSize: "16px", marginBottom: "10px" }}
/>
<p>Your Name: {name}</p>
</div>
);
}

function App() {
return <NameForm />;
}

export default App;

Step 2: Execute the Code

1. Save all files.


2. Run the React app using:

npm start
3. Open http://localhost:3000/ in a browser.
4. Type your name into the input field and see it dynamically update below.

Result:

 Successfully created a controlled component where React controls the input field.
 The displayed text updates in real-time as the user types.
Experiment 8: Basic Routing in React
Aim: To implement basic routing in a React application using BrowserRouter.

Objective:

1. Learn how to set up React Router.


2. Configure routes using <Route>.
3. Navigate between pages using <Link>.

Theory:

 React Router allows navigation between different components without refreshing the page.
 <BrowserRouter> enables clean URLs.
 <Route> defines which component to load based on the URL.
 <Link> provides navigation without reloading the page.

Code Implementation:

Step 1: Install React Router

npm install react-router-dom

Step 2: Configure Routes in App.js

Modify src/App.js:

import React from "react";


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

function App() {
return (
<Router>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}
export default App;

Step 3: Create Page Components

Home.js

import React from "react";


function Home() {
return <h1>Home Page</h1>;
}
export default Home;

About.js

import React from "react";


function About() {
return <h1>About Us</h1>;
}
export default About;

Contact.js

import React from "react";


function Contact() {
return <h1>Contact Us</h1>;
}
export default Contact;

Step 4: Execute the Code

npm start

Open http://localhost:3000/ and navigate between Home, About, and Contact.

Result:

 Successfully implemented basic routing in a React app.


 Navigation between pages happens without refreshing.
Experiment 9: Nested Routing in React
Aim: To implement nested routes, allowing sub-pages within a main page.

Objective:

1. Learn how to create routes within routes.


2. Use the <Outlet> component to render nested routes.

Theory:

 Nested routes allow structuring related pages inside a parent route.


 <Outlet> renders child routes dynamically based on the URL.

Code Implementation:

Step 1: Modify App.js to Include Nested Routes

import React from "react";


import { BrowserRouter as Router, Route, Routes, Link } from "react-
router-dom";
import Home from "./Home";
import Dashboard from "./Dashboard";
import Profile from "./Profile";
import Settings from "./Settings";

function App() {
return (
<Router>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/dashboard">Dashboard</Link></li>
</ul>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard/*" element={<Dashboard />} />
</Routes>
</Router>
);
}

export default App;

Step 2: Create Dashboard.js with Nested Routes

import React from "react";


import { Routes, Route, Link, Outlet } from "react-router-dom";
import Profile from "./Profile";
import Settings from "./Settings";

function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<nav>
<ul>
<li><Link to="profile">Profile</Link></li>
<li><Link to="settings">Settings</Link></li>
</ul>
</nav>

<Outlet />

<Routes>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Routes>
</div>
);
}

export default Dashboard;

Step 3: Create Profile.js and Settings.js

Profile.js

import React from "react";


function Profile() {
return <h2>User Profile</h2>;
}
export default Profile;

Settings.js

import React from "react";


function Settings() {
return <h2>Settings Page</h2>;
}
export default Settings;

Step 4: Execute the Code

npm start

Visit http://localhost:3000/dashboard, then click Profile and Settings.

Result:

 Implemented nested routing inside the Dashboard.


 Used <Outlet> to render child routes dynamically.
Experiment 10: Implementing Protected Routes
Aim: To restrict access to a route unless the user is authenticated.

Objective:

1. Implement a protected route that only allows access if a user is logged in.
2. Redirect users to the login page if they are not authenticated.

Theory:

 A protected route checks if the user is authenticated before rendering a component.


 If unauthenticated, it redirects to a login page.

Code Implementation:

Step 1: Create a Fake Authentication System

Create Auth.js in src/ folder:

const Auth = {
isAuthenticated: false,
login(cb) {
Auth.isAuthenticated = true;
cb();
},
logout(cb) {
Auth.isAuthenticated = false;
cb();
},
};

export default Auth;

Step 2: Create a Protected Route Component

Create ProtectedRoute.js:

import React from "react";


import { Navigate } from "react-router-dom";
import Auth from "./Auth";

function ProtectedRoute({ children }) {


return Auth.isAuthenticated ? children : <Navigate to="/login" />;
}

export default ProtectedRoute;

Step 3: Modify App.js to Use Protected Routes

import React from "react";


import { BrowserRouter as Router, Route, Routes, Link } from "react-
router-dom";
import Home from "./Home";
import Dashboard from "./Dashboard";
import Login from "./Login";
import ProtectedRoute from "./ProtectedRoute";

function App() {
return (
<Router>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/dashboard">Dashboard</Link></li>
</ul>
</nav>

<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
</Routes>
</Router>
);
}

export default App;

Step 4: Create Login.js

import React from "react";


import { useNavigate } from "react-router-dom";
import Auth from "./Auth";

function Login() {
const navigate = useNavigate();

function handleLogin() {
Auth.login(() => navigate("/dashboard"));
}

return (
<div>
<h2>Login Page</h2>
<button onClick={handleLogin}>Login</button>
</div>
);
}

export default Login;

Result:

 Users must log in before accessing the dashboard.


 Unauthenticated users are redirected to the login page.

You might also like