What are props in 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.
Related React job interview questions
What is a controlled component in React?
React JuniorHow is state different than props in React?
React JuniorWhat is mounted component in React?
React JuniorWhich methods would you use to handle events in React?
React JuniorHow would you avoid binding in React?
React Junior