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.

Setting attributes

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".

Include data

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.

Pass down props

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.

Key Takeaways

  • To pass props to a component in React, you can set attributes on the component when it is used in another component.
  • You can include any data you want as key-value pairs when you pass props to a component.
  • You can pass down props from a parent component to a child component using the same method.
  • By passing props between components, you can easily share data and functionality throughout your React application.

FAQ

What are props in React?
Props are short for properties. They are data that is passed from a parent component to a child component.
How do I set props in React?
To set props in React, you can use the props object when you render the component.
What are the benefits of passing props in React?
There are many benefits to passing props in React, including:

  • It allows you to share data and functionality between components.
  • It makes your code more modular and reusable.
  • It makes your code easier to test.

Leave a Reply

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