Let's get started by building our first React component! Here's a simple example that displays a greeting message:
function Greeting() {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
}
This code defines a function named "Greeting" that returns JSX code. The JSX code defines a "div" element containing an "h1" element with the text "Hello, World!". This component can be reused throughout your application to display the greeting message.
JSX (JavaScript XML) is a syntax extension that allows you to write component code resembling HTML. It improves readability by combining the familiarity of HTML with the power of JavaScript. Within JSX, you write HTML-like tags that represent UI elements, and you can embed JavaScript expressions within those tags using curly braces ("{}").
Here are some key points about JSX:
Components often need to receive data from other components to customize their behavior and appearance. This data is passed down through properties (props). Props are read-only values that a component receives from its parent component.
Let's modify the "Greeting" component to accept a name as a prop:
function Greeting(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
}
In this example, the "Greeting" component now takes a single prop named "name". Inside the JSX, we use curly braces to access the "name" prop and dynamically render the greeting message with the provided name.
Props are like arguments passed to a function, but instead of being passed during the function call, they are provided when the component is used. Here's a breakdown of how props work in your example:
<Greeting name="Alice" /> // Pass "Alice" as the value for the "name" prop
Inside the Greeting component, you access props.name to retrieve the value ("Alice" in this case) and display it within the <h1> element.
We'll explore using components and props in more detail in the following chapters, along with advanced concepts like state management and lifecycle methods. Stay tuned!
Homepage: Rendering Components