Understanding JSX
JSX (JavaScript XML) is a syntax extension for JavaScript used in React to describe what the UI should look like. It allows you to write HTML-like code directly in your JavaScript files.
const element = <h1>Hello, world!</h1>;
JSX makes your code more readable and expressive. Under the hood, it gets transformed into regular JavaScript using
React.createElement()
.
Note: JSX requires elements to be properly closed and wrapped in a single parent element.
Components: Functional vs Class
In React, components are the building blocks of the UI. There are two main types:
Functional Components (Modern)
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
Functional components are simpler and support Hooks, which allow you to manage state and lifecycle features without a class.
Class Components (Legacy)
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Class components were commonly used before the introduction of Hooks in React 16.8. Today, functional components are preferred.
Props and State
Props (Short for Properties)
Props are used to pass data from a parent component to a child component. They are read-only and cannot be modified by the child component.
function Greeting(props) {
return <p>Welcome, {props.user}!</p>;
}
State
State is used to store local data within a component. It can be updated using the useState
Hook.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Handling Events in React
Event handling in React is similar to handling events in plain HTML/JS, but with camelCase syntax and JSX formatting.
function Button() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick={handleClick}>Click Me</button>;
}
You can also pass inline functions or parameters using arrow functions.
<button onClick={() => console.log('Clicked!')}>Click</button>
Conclusion
In this post, you’ve learned the core fundamentals of React: JSX, components, props, state, and event handling. These concepts form the foundation of every React application. In the next post, we’ll explore how to style React components using different techniques like inline styles, CSS modules, and styled-components.
0 Comments