How do you pass data to React components?
Answer
In React, data can be passed to components through props. Props are short for properties and are used to pass data from a parent component to a child component.
The parent component can pass any data type as a prop, including strings, numbers, objects, and functions. The child component can then access the data passed through props and use it to render its content.
To pass data through props, the parent component needs to define the prop and its value when rendering the child component.
For example, if we have a parent component called App and a child component called Button, we can pass a prop called buttonText to the Button component like this:
<Button buttonText="Click me!" />
In the Button component, we can access the buttonText prop using the props object:
function Button(props) {
return <button>{props.buttonText}</button>;
}
This will render a button with the text "Click me!". Props can also be used to pass functions as data to child components. For example, if we have a parent component called App and a child component called Input, we can pass a function called handleChange to the Input component like this:
<Input handleChange={this.handleInputChange} />
In the Input component, we can access the handleChange function using the props object:
function Input(props) {
return <input type="text" onChange={props.handleChange} />;
}
This will render an input field that calls the handleChange function whenever the user types something in the field.
Related React job interview questions
Why do we need keys for React lists?
React JuniorWhat are React fragments used for?
React JuniorHow is React shadow DOM different than virtual DOM?
React JuniorWhat is React virtual DOM?
React JuniorWhat is React shadow DOM?
React Junior