What are props in React?

Experience Level: Junior
Tags: React

Answer

In React, props (short for properties) are a way to pass data from a parent component to a child component. They are read-only and cannot be modified by the child component. Props are passed down as attributes to the child component in JSX. The child component can then access the props using the this.props object.

Props are useful for creating reusable components. For example, if you have a Button component that you want to use in multiple places in your application, you can pass different text and styles to the Button component using props. This allows you to create a generic Button component that can be customized for different use cases.


// Example of passing props to a child component

// Parent component
function App() {
  return (
    <div>
      <Button text="Click me!" color="blue" />
      <Button text="Submit" color="green" />
    </div>
  );
}

// Child component
function Button(props) {
  return (
    <button style={{ backgroundColor: props.color }}>
      {props.text}
    </button>
  );
}

In the above example, the App component is passing different text and color props to the Button component. The Button component then uses these props to render a button with the appropriate text and background color.

React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself