React components and JSX (JavaScript XML) are at the core of React applications. This tutorial will introduce you to creating components and using JSX to render UI elements dynamically.
React Components and JSX
1. What is a React Component?
In React, components are reusable UI elements that make up an application. A component is a JavaScript function or class that accepts inputs (known as props) and returns React elements to render the UI.
Components are the building blocks of a React app, making it easier to manage complex UIs by breaking them into smaller, isolated pieces.
2. What is JSX?
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML elements in JavaScript and place them in the DOM without using createElement()
or appendChild()
. JSX makes it easier to write and visualize UI code in React.
Example JSX code:
<div>Hello, World!</div>
This code creates a div
element that displays "Hello, World!" on the screen.
3. Creating a Functional Component
A functional component is a JavaScript function that returns a React element. Here’s an example of a simple functional component:
function Greeting() {
return <h1>Hello, React!</h1>;
}
To use this component, you can include it within other components or directly in the main render method:
<Greeting />
4. Using Props in Components
Props (short for "properties") allow you to pass data to components. Here’s an example of a component that takes a name
prop and displays it:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
To use the Welcome
component and pass a name, use the following syntax:
<Welcome name="Alice" />
5. Class Components
Class components are another way to define components in React. While functional components are preferred in modern React, class components are still widely used. Here’s an example:
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
6. Conclusion
Now you know the basics of React components and JSX. Components make React applications scalable and reusable, while JSX allows you to write HTML-like syntax directly in JavaScript. Practice creating components and passing data with props to deepen your understanding.