Sobes.tech
Junior

What are props in the context of React?

sobes.tech AI

Answer from AI

props (from the English word 'properties') in React is an object containing data passed from a parent component to a child. They are accessible within the child component only for reading and represent the main mechanism for passing information down the component tree.

Main characteristics of props:

  • Data transfer: Used to pass data, configurations, and callbacks from parent to child.
  • Immutability: Inside the child component, props cannot be modified. Any changes should originate from the parent component, which passes new props.
  • Object: props are always passed as an object. Each property passed becomes a key in this object.
  • Access: In functional components, props are passed as the first argument of the function. In class components, they are accessible via this.props.

Example of passing and using props:

// Parent component
function ParentComponent() {
  const greeting = "Hello";
  return <ChildComponent message={greeting} />;
}

// Child component
function ChildComponent(props) {
  return <p>{props.message}, world!</p>;
}