// App.js - Basic React Component
import React from "react";
const App = () => {
return (
<div>
<h2>Hello, React!</h2>
</div>
);
};
export default App;
// Functional Component with Props
import React from "react";
const Greeting = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
export default Greeting;
// Class Component
import React, { Component } from "react";
class App extends Component {
render() {
return <h2>Welcome to React Class Component!</h2>;
}
}
export default App;
// useState Hook Example
import React, { useState } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
};
export default Counter;
// useEffect Hook Example
import React, { useState, useEffect } from "react";
const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => setSeconds(seconds + 1), 1000);
return () => clearInterval(interval);
}, [seconds]);
return <p>Timer: {seconds} seconds</p>;
};
export default Timer;
// Handling Events in React
import React from "react";
const ClickButton = () => {
const handleClick = () => {
alert("Button clicked!");
};
return <button onClick={handleClick}>Click Me</button>;
};
export default ClickButton;
// Conditional Rendering Example
import React from "react";
const App = () => {
const isLoggedIn = true;
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>}
</div>
);
};
export default App;
// React Context API Example
import React, { createContext, useState, useContext } from "react";
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
const ThemeButton = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Switch to {theme === "light" ? "dark" : "light"} theme
</button>
);
};
export { ThemeProvider, ThemeButton };
// Simple Form Example
import React, { useState } from "react";
const FormExample = () => {
const [name, setName] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was: ${name}`);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
};
export default FormExample;