How to pass props in React

In React, you can pass props to a component by setting attributes on the component when it is used in another component. Here’s an example:

function MyComponent(props) {
  return <h1>Hello, {props.name}!</h1>;
}

function App() {
  return <MyComponent name="Alice" />;
}

In this example, the MyComponent function takes a props object as an argument, which we use to render a personalized greeting. The App function renders the MyComponent function, passing in the name prop with a value of "Alice".

When you pass props to a component, you can include any data you want as key-value pairs. Here’s an example of passing multiple props:

function MyComponent(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>You are {props.age} years old.</p>
    </div>
  );
}

function App() {
  return <MyComponent name="Alice" age={30} />;
}

In this example, the MyComponent function receives two props: name and age. The name prop is a string with a value of "Alice", while the age prop is a number with a value of 30.

You can also pass down props from a parent component to a child component using the same method:

function ParentComponent() {
  const name = "Alice";
  return <ChildComponent name={name} />;
}

function ChildComponent(props) {
  return <h1>Hello, {props.name}!</h1>;
}

In this example, the ParentComponent function sets the name variable to "Alice", and then renders the ChildComponent function, passing in the name prop. The ChildComponent function receives the name prop and renders a personalized greeting.

By passing props between components, you can easily share data and functionality throughout your React application.

Leave a Reply

Your email address will not be published. Required fields are marked *