up:: [[React MOC]]
tags:: #on/computing/programming
# React Props
*Props* are a way to pass data between [[React Components|React components]].
## Defining Props
Props are similar to parameters for functions. Take this example of a simple button component:
```jsx
const Button = () => {
const text = "Click me!";
return (
<button>{text}</button>
);
};
```
Now, what would we do if we wanted to display dynamic text on the button? We would add a prop for the text.
To add props to a function component, specify a parameter in the component's definition:
```jsx
const Button = (props) => {
return (
<button>{props.text}</button>
);
};
```
In this case, we're calling the parameter `props`. This parameter is always taken as an object and is always first in the component's signature, which means it can be destructured to extract its contents:
```jsx
const Button = ({ text }) => {
return (
<button>{text}</button>
);
};
```
To pass prop data to a component, specify it in JSX:
```jsx
const Button = ({ text }) => {
return (
<button>{text}</button>
);
};
const Modal = () => {
return (
<Button text="Click me!" />
);
};
```
To pass data that is not a string literal, use curly braces:
```jsx
const Button = ({ text }) => {
return (
<button>{text}</button>
);
};
const Modal = () => {
const buttonText = "Click me!";
return (
<Button text={buttonText} />
);
};
```
> [!NOTE]
> Props are read-only. You cannot modify their values within a component.
> [!NOTE]
> There is no way to pass data from a child component to a parent component using props. Props can only be passed from parent to child.
## Props vs. State
Component props are immutable, which means passing them between components won't make them interactive. If you want to have interactive components, use [[React State|state]] instead. Remember, props are just a vehicle for passing information, while state can be changed over time.
## References
Wieruch, Robin. “How to Use Props in React,” March 25, 2022. [https://www.robinwieruch.de/react-pass-props-to-component/](https://www.robinwieruch.de/react-pass-props-to-component/).