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,
propscannot be modified. Any changes should originate from the parent component, which passes newprops. - Object:
propsare always passed as an object. Each property passed becomes a key in this object. - Access: In functional components,
propsare passed as the first argument of the function. In class components, they are accessible viathis.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>;
}