Understanding React fundamentals is crucial for building robust applications. Let's explore the core concepts that make React so powerful.
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code within JavaScript.
const element = <h1>Hello, React!</h1>;
<> or React.Fragment to wrap multiple elementsclassName instead of class)// Good
const MyComponent = () => {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
};
React applications are built using components. There are two main types:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Or with arrow function
const Welcome = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Modern React: We recommend using functional components with hooks for new projects.
Props are how components communicate with each other. They're read-only and help make components reusable.
const UserCard = ({ name, email, age }) => {
return (
<div className="user-card">
<h2>{name}</h2>
<p>Email: {email}</p>
<p>Age: {age}</p>
</div>
);
};
// Usage
<UserCard name="John Doe" email="john@example.com" age={30} />
The Virtual DOM is a JavaScript representation of the real DOM. React uses it to:
This process is called "reconciliation" and makes React applications fast and responsive.
React uses SyntheticEvents, which wrap native events and provide a consistent API across browsers.
const Button = () => {
const handleClick = (event) => {
event.preventDefault();
console.log('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
};
You can conditionally render elements in React using JavaScript operators:
const Greeting = ({ isLoggedIn, user }) => {
return (
<div>
{isLoggedIn ? (
<h1>Welcome back, {user.name}!</h1>
) : (
<h1>Please log in.</h1>
)}
</div>
);
};
When rendering lists, always provide a unique key prop:
const TodoList = ({ todos }) => {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
{todo.text}
</li>
))}
</ul>
);
};
Now that you understand React fundamentals, you're ready to dive deeper into:
Practice these concepts by building small projects—the more you code, the more natural React will become!