React Assignment

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

ASSIGNMENT ( REACT)

1. Installing react router:


npm install react-router-dom
Setting up routes:
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import Home from './Home';
import Dashboard from './Dashboard';
import Login from './Login';

const App = () => {


const [loggedIn, setLoggedIn] = useState(false);

const login = () => {


setLoggedIn(true);
};

const logout = () => {


setLoggedIn(false);
};

return (
<Router>
<div>
<Route exact path="/" component={Home} />
<Route
path="/dashboard"
render={() =>
loggedIn ? <Dashboard logout={logout} /> : <Redirect to="/login" />
}
/>
<Route
path="/login"
render={() => (loggedIn ? <Redirect to="/dashboard" /> : <Login login={login} />)}
/>
</div>
</Router>
);
};

export default App;

Home.js:
import React from 'react';

const Home = () => {


return <div>Welcome to our website!</div>;
};

export default Home;

Dashboard.js:
import React from 'react';

const Dashboard = ({ logout }) => {


return (
<div>
<h2>Dashboard</h2>
<button onClick={logout}>Logout</button>
</div>
);
};

export default Dashboard;

Login.js:
import React from 'react';

const Login = ({ login }) => {


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

export default Login;

2. Setting up project:
npx create-react-app my-app
cd my-app
npm install react-router-dom

Setting up routing:
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import LoginForm from './LoginForm';
import SignupForm from './SignupForm';
import Dashboard from './Dashboard';

function App() {
const [loggedIn, setLoggedIn] = useState(false);
const [users, setUsers] = useState([]);

const handleLogin = () => {


// Perform login logic here (e.g., check credentials)
setLoggedIn(true);
};

const handleSignup = (user) => {


// Add new user to the list of users
setUsers([...users, user]);
};

return (
<Router>
<div>
<Switch>
<Route exact path="/">
<Redirect to="/login" />
</Route>
<Route path="/login">
<LoginForm onLogin={handleLogin} />
</Route>
<Route path="/signup">
<SignupForm onSignup={handleSignup} />
</Route>
<Route path="/dashboard">
{loggedIn ? <Dashboard users={users} /> : <Redirect to="/login" />}
</Route>
</Switch>
</div>
</Router>
);
}

export default App;

Creating a LoginForm.js:
import React, { useState } from 'react';

const LoginForm = ({ onLogin }) => {


const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
// Validate login credentials here (e.g., check against database)
onLogin();
};

return (
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Username" value={username} onChange={(e) =>
setUsername(e.target.value)} />
<input type="password" placeholder="Password" value={password} onChange={(e) =>
setPassword(e.target.value)} />
<button type="submit">Login</button>
</form>
</div>
);
};

export default LoginForm;

Creating the SignupForm.js component:


import React, { useState } from 'react';

const SignupForm = ({ onSignup }) => {


const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
const newUser = { username, password };
// Validate signup details here (e.g., check for unique username)
onSignup(newUser);
setUsername('');
setPassword('');
};

return (
<div>
<h2>Sign Up</h2>
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Username" value={username} onChange={(e) =>
setUsername(e.target.value)} />
<input type="password" placeholder="Password" value={password} onChange={(e) =>
setPassword(e.target.value)} />
<button type="submit">Sign Up</button>
</form>
</div>
);
};

export default SignupForm;

Dashboard.js component:
import React from 'react';
const Dashboard = ({ users }) => {
return (
<div>
<h2>Dashboard</h2>
<ul>
{users.map((user, index) => (
<li key={index}>{user.username}</li>
))}
</ul>
</div>
);
};

export default Dashboard;

3. import React, { Component } from 'react';

class MyComponent extends Component {


constructor(props) {
super(props);
this.state = {
message: ''
};
console.log('Constructor');
}

componentDidMount() {
console.log('Component Did Mount');
this.setState({ message: 'Component is mounted!' });
}

componentDidUpdate() {
console.log('Component Did Update');
}

componentWillUnmount() {
console.log('Component Will Unmount');
}

render() {
console.log('Render');
return <div>{this.state.message}</div>;
}
}

export default MyComponent;

4. Parent Component:
import React from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const product = {
id: 1,
name: 'Product Name',
price: 10.99
};

return (
<div>
<h2>Parent Component</h2>
<ChildComponent product={product} />
</div>
);
};

export default ParentComponent;

Child component:
import React from 'react';

const ChildComponent = (props) => {


const { product } = props;

return (
<div>
<h3>Child Component</h3>
<p>ID: {product.id}</p>
<p>Name: {product.name}</p>
<p>Price: ${product.price}</p>
</div>
);
};

export default ChildComponent;

5. Using Axios:
import React, { useState } from 'react';
import axios from 'axios';

const PostRequest = () => {


const [postData, setPostData] = useState({ title: '', body: '' });

const handleChange = (e) => {


setPostData({ ...postData, [e.target.name]: e.target.value });
};

const handleSubmit = async (e) => {


e.preventDefault();
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', postData);
console.log('Response from Axios:', response.data);
} catch (error) {
console.error('Error:', error);
}
};

return (
<div>
<h2>Post Request using Axios</h2>
<form onSubmit={handleSubmit}>
<input type="text" name="title" placeholder="Title" value={postData.title}
onChange={handleChange} />
<textarea name="body" placeholder="Body" value={postData.body}
onChange={handleChange} />
<button type="submit">Submit</button>
</form>
</div>
);
};

export default PostRequest;

Using Fetch API:


import React, { useState } from 'react';

const PostRequest = () => {


const [postData, setPostData] = useState({ title: '', body: '' });

const handleChange = (e) => {


setPostData({ ...postData, [e.target.name]: e.target.value });
};

const handleSubmit = (e) => {


e.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then((response) => response.json())
.then((data) => {
console.log('Response from Fetch:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
return (
<div>
<h2>Post Request using Fetch API</h2>
<form onSubmit={handleSubmit}>
<input type="text" name="title" placeholder="Title" value={postData.title}
onChange={handleChange} />
<textarea name="body" placeholder="Body" value={postData.body}
onChange={handleChange} />
<button type="submit">Submit</button>
</form>
</div>
);
};

export default PostRequest;

You might also like