Getting Started
3 snippetsJSX basics with React
Basic Component
import React from 'react';
const HelloWorld = () => {
return <h1>Hello, World!</h1>;
};
export default HelloWorld;JSX Expressions
const name = 'John';
const age = 30;
const Greeting = () => (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old</p>
<p>Next year: {age + 1}</p>
</div>
);JSX Attributes
const Image = () => (
<img
src="/logo.png"
alt="Logo"
className="logo-image"
width={200}
height={100}
/>
);Props
4 snippetsPassing data to components
Basic Props
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
// Usage
<Greeting name="World" />Destructured Props
const UserCard = ({ name, email, age }) => (
<div className="card">
<h2>{name}</h2>
<p>{email}</p>
<p>Age: {age}</p>
</div>
);
// Usage
<UserCard name="John" email="john@example.com" age={30} />Default Props
const Button = ({ label = 'Click Me', disabled = false }) => (
<button disabled={disabled}>{label}</button>
);Children Prop
const Card = ({ title, children }) => (
<div className="card">
<h2>{title}</h2>
<div className="content">
{children}
</div>
</div>
);
// Usage
<Card title="My Card">
<p>This is the content</p>
</Card>State Management
3 snippetsManaging component state
useState Hook
import { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
};Multiple State Variables
const LoginForm = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
setIsLoading(true);
// Submit logic
};
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<input value={password} onChange={(e) => setPassword(e.target.value)} />
<button disabled={isLoading}>Login</button>
</form>
);
};State with Objects
const UserProfile = () => {
const [user, setUser] = useState({
name: '',
email: '',
age: 0
});
const updateName = (name) => {
setUser({ ...user, name });
};
return <div>{user.name}</div>;
};Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Side Effects
3 snippetsuseEffect hook
Basic useEffect
import { useEffect, useState } from 'react';
const DataFetcher = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(data => setData(data));
}, []);
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
};Effect with Dependencies
const SearchResults = ({ query }) => {
const [results, setResults] = useState([]);
useEffect(() => {
if (query) {
fetch(`/api/search?q=${query}`)
.then(res => res.json())
.then(data => setResults(data));
}
}, [query]);
return <div>{results.length} results</div>;
};Cleanup Function
const Timer = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>{seconds} seconds</div>;
};Event Handling
4 snippetsHandling user interactions
Click Events
const Button = () => {
const handleClick = () => {
console.log('Button clicked');
};
return <button onClick={handleClick}>Click Me</button>;
};Input Events
const TextInput = () => {
const [value, setValue] = useState('');
const handleChange = (e) => {
setValue(e.target.value);
};
return <input value={value} onChange={handleChange} />;
};Form Submit
const LoginForm = () => {
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
console.log(Object.fromEntries(formData));
};
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" />
<input name="password" type="password" />
<button type="submit">Login</button>
</form>
);
};Event with Parameters
const ItemList = ({ items }) => {
const handleClick = (id) => {
console.log('Clicked item:', id);
};
return (
<ul>
{items.map(item => (
<li key={item.id} onClick={() => handleClick(item.id)}>
{item.name}
</li>
))}
</ul>
);
};Conditional Rendering
3 snippetsShowing/hiding content
If-Else with Ternary
const LoginStatus = ({ isLoggedIn }) => (
<div>
{isLoggedIn ? (
<button>Logout</button>
) : (
<button>Login</button>
)}
</div>
);Logical AND
const Notification = ({ message }) => (
<div>
{message && <div className="alert">{message}</div>}
</div>
);Multiple Conditions
const StatusBadge = ({ status }) => (
<div>
{status === 'success' && <span className="badge-success">✓</span>}
{status === 'error' && <span className="badge-error">✗</span>}
{status === 'pending' && <span className="badge-pending">⏳</span>}
</div>
);Lists & Keys
3 snippetsRendering arrays
Basic List
const TodoList = ({ todos }) => (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);List with Components
const UserList = ({ users }) => (
<div>
{users.map(user => (
<UserCard key={user.id} user={user} />
))}
</div>
);Filtered List
const ActiveTodos = ({ todos }) => {
const activeTodos = todos.filter(todo => !todo.completed);
return (
<ul>
{activeTodos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
};Styling
3 snippetsCSS and inline styles
Inline Styles
const StyledDiv = () => {
const styles = {
backgroundColor: 'blue',
color: 'white',
padding: '10px',
borderRadius: '5px'
};
return <div style={styles}>Styled Content</div>;
};CSS Classes
import './Button.css';
const Button = ({ variant }) => (
<button className={`btn btn-${variant}`}>
Click Me
</button>
);Dynamic Classes
const Alert = ({ type, message }) => {
const className = `alert ${type === 'error' ? 'alert-error' : 'alert-success'}`;
return <div className={className}>{message}</div>;
};