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

React Ans Key

Uploaded by

thiru252627
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

React Ans Key

Uploaded by

thiru252627
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

->React Ans Key:

1.)Error Boundary
ErrorBoundary.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export class ErrorBoundary extends Component {
constructor(props) {
super(props)
this.state = {
hasError: false
}
}
static getDerivedStateFromError(error) {
return {
hasError: true
}
}
render() {
if (this.state.hasError === true) {
return <h1>Something went wrong</h1>
}
return this.props.children
}
}
App.jsx
import React from 'react';
import PropTypes from 'prop-types';
const Hero = ({ heroName }) => {
if (heroName === 'Joker') {
throw new Error('Not a hero');
}
return (
<div>
{heroName}
</div>
)
}
Hero.propTypes = {
heroName: PropTypes.string.isRequired
}
export default Hero;

2.)Create A Hello World Application (Function


Component)
HelloWorld.jsx:
import React from 'react';
function HelloWorld()
{
return(
<div>
<p>Hello, World!</p>
</div>
);
}
export default HelloWorld;
App.js:
import React from 'react';
import HelloWorld from './components/HelloWorld'; function
App()
{
return (
<div>
<HelloWorld/>
</div>
);
}
export default App;
3.)Inline Styling
InlineStyling.jsx
import React from 'react';

const InlineStyling = () => {


return (
<div>
<h1 style={{ color: 'green' }}>Inline Style in JSX
Example.</h1>
<div style={{ backgroundColor: 'lightblue', color:
'darkblue', padding: '10px', border: '1px solid blue',
borderRadius: '5px' }}>
<p style={{ color: 'darkblue', fontSize: '16px' }}>This is
a paragraph with inline styles applied.</p>
</div>
</div>
)
}
export default InlineStyling;
App.jsx
import React from 'react';
import './assets/css/App.css';
import InlineStyling from './components/InlineStyling';
function App() {
return (
<div className="App">
<InlineStyling />
</div>
);
}
export default App;
4.)Counter App using Redux
Counter.jsx
import React from 'react'
import { decrement, increment } from '../redux/CounterAction';
import { useDispatch, useSelector } from 'react-redux';
const Counter = () => {
const dispatch = useDispatch();
const count = useSelector((state) => state.count);
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
dispatch(decrement())}>Decrement</button>
<button onClick={() =>
dispatch(increment())}>Increment</button>
</div>
)
}
export default Counter;
CounterAction.jsx
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const increment = () => ({
type: INCREMENT
})
export const decrement = () => ({
type: DECREMENT
})

CounterReducer.jsx
import { DECREMENT, INCREMENT } from "./CounterAction";
const initialState = {
count: 0
}
const CounterReducer = (state = initialState, action) => {
switch (action.type) {
case INCREMENT:
return { count: state.count + 1 }
case DECREMENT:
return { count: state.count - 1 }
default:
return state;
}
}
export default CounterReducer;

Store.jsx
import { configureStore } from "@reduxjs/toolkit";
import CounterReducer from "./CounterReducer";
export const Store = configureStore({
reducer: CounterReducer
})
App.jsx
import React from 'react';
import './assets/css/App.css';
import { Provider } from 'react-redux';
import Counter from './components/Counter';
import { Store } from './redux/Store';
function App() {
return (
<Provider store={Store}>
<div className="App">
<Counter />
</div>
</Provider>
);
}
export default App;

5.)Theme App using Redux


Theme.jsx
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { toggleTheme } from '../redux/ThemeAction';
const Theme = () => {
const dispatch = useDispatch();
const theme = useSelector((state) => state.theme);
const style = {
width: '100%',
height: '100vh',
backgroundColor: theme,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}
const btn = {
backgroundColor: 'gray',
color: 'white',
padding: '10px',
cursor: 'pointer',
}

return (
<div style={style} data-testid='theme-container'>
<button style={{ ...btn, width: '120px' }} onClick={() =>
dispatch(toggleTheme())}>Theme</button>
</div>
)
}

export default Theme;

Store.jsx
import { configureStore } from "@reduxjs/toolkit";
import ThemeReducer from "./ThemeReducer";
export const Store = configureStore({
reducer: ThemeReducer
})
export const TOGGLE_THEME = 'TOGGLE_THEME'

ThemeAction.jsx

export const toggleTheme = () => ({


type: TOGGLE_THEME
})

ThemeReducer.jsx
import { TOGGLE_THEME } from "./ThemeAction";
const initialState = {
theme: 'black'
}
const ThemeReducer = (state = initialState, action) => {
switch (action.type) {
case TOGGLE_THEME:
return { ...state, theme: state.theme === 'black' ? 'white'
: 'black' }
default:
return state;
}
}
export default ThemeReducer;

App.jsx
import React from 'react';
import './assets/css/App.css';
import { Provider } from 'react-redux';
import { Store } from './redux/Store';
import Theme from './components/Theme';

function App() {
return (
<Provider store={Store}>
<div className="App">
<Theme />
</div>
</Provider>
);
}
export default App;
6.)Create A Hello World Application (Class
Component)
HelloWorld.jsx
import React from 'react';
import {Component} from 'react';
class HelloWorld extends Component
{
render()
{
return(
<div>
<p>Hello, World!</p>
</div>
);
}
}
export default HelloWorld;
App.jsx
import React from 'react';
import HelloWorld from './components/HelloWorld'; function
App()
{
return (
<div>
<HelloWorld/>
</div>
);
}
export default App;
7.)Display data using Props
Displaydata.jsx
import React from 'react'
import PropTypes from 'prop-types';
const DisplayData = (props) => {
return (
<div>
<h2>Static Data:</h2>
<p>{props.staticData}</p>
<h2>Dynamic Data:</h2>
<p>{props.dynamicData}</p>
</div>
)
}
DisplayData.propTypes = {
staticData: PropTypes.string.isRequired,
dynamicData: PropTypes.node.isRequired
}
export default DisplayData;
App.jsx
import React from 'react';
import './assets/css/App.css';
import DisplayData from './components/DisplayData';
function App() {
const dynamicData = new Date().toLocaleString();
return (
<div className="App">
<h1>Props Demo</h1>
<DisplayData staticData="Hello, I am static data!"
dynamicData={dynamicData} />
</div>
);
}
export default App;
8.)Browser Routing
About.jsx
import React from 'react';
const About = () => {
return (
<div>
<h2>About</h2>
<p>This is the about page.</p>
</div>
)
}
export default About;
Home.jsx
import React from 'react';
const Home = () => {
return (
<div>
<h2>Home</h2>
<p>Welcome to the home page!</p>
</div>
)
}
export default Home;

Navbar.jsx
import React from 'react';
import { Link } from 'react-router-dom';
import '../assets/css/Navbar.css';
const Navbar = () => {
return (
<div className='navbar-container'>
<ul className='nav-links'>
<li className='nav-link'><Link className="home"
to={`/`}>Home</Link></li>
<li className='nav-link'><Link className="about"
to={`/about`}>About</Link></li>
</ul>
</div>
)
}
export default Navbar;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './assets/css/index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter} from 'react-router-dom';

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
reportWebVitals();
App.jsx
import React from 'react';
import './assets/css/App.css';
import { Route, Routes } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Navbar from './components/Navbar';
function App() {
return (
<div className="App">
<Navbar />
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/about' element={<About />} />
</Routes>
</div>
);
}
export default App;
9.)Card Component with Material-UI
CustomCard.jsx
import React from 'react';
import { Button, Card, CardActions, CardContent, CardMedia,
Typography } from '@mui/material';
import Tree from '../assets/images/tree.jpg';
const CustomCard = () => {
return (
<Card sx={{ maxWidth: 345 }}>
<CardMedia
sx={{ height: 140 }}
image={Tree}
title="Tree"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
Nature
</Typography>
<Typography variant="body2" color="text.secondary">
In the embrace of nature, the symphony of chirping birds
and the gentle caress of a breeze paint a serene canvas of
tranquility.
</Typography>
</CardContent>
<CardActions>
<Button size="small">Share</Button>
<Button size="small">Learn More</Button>
</CardActions>
</Card>
)
}
export default CustomCard;
App.jsx
import React from 'react';
import './assets/css/App.css';
import CustomCard from './components/CustomCard';
function App() {
return (
<div className="App">
<CustomCard />
</div>
);
}
export default App;
10.)Login Form using useRef
Form.jsx
import React, { useRef } from 'react';
import '../assets/css/Form.css';
const LoginForm = () => {
const emailInputRef = useRef(null);
const passwordInputRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
const formData = {
email: emailInputRef.current.value,
password: passwordInputRef.current.value
};
console.log(formData);
emailInputRef.current.value = '';
passwordInputRef.current.value = '';
emailInputRef.current.focus();
}

return (
<div className='form__container'>
<form className='register__form' method='POST'
onSubmit={handleSubmit}>
<div className="input__fields">
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
required
ref={emailInputRef}
/>
</div>
<div className="input__fields">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="password"
required
minLength={8}
maxLength={15}
ref={passwordInputRef}
/>
</div>
<button className='submit__btn'
type="submit">Login</button>
</form>
</div>
);
}
export default LoginForm;
App.jsx
import React from 'react';
import './assets/css/App.css';
import LoginForm from './components/Form';
function App() {
return (
<div className="App">
<LoginForm />
</div>
);
}
export default App;

You might also like