We can pass variables into a component from outside and take them from the props object. Take variables from props object
const Component1 = (props) => <div>{props.a}, {props.b} dear {props.c}!</div>
<Component1 a='hello' b='my' c='friend'/>
Destructure props object in component
const Component2 = ({ a, b, c }) => <div>{a}, {b} dear {c}!</div>
<Component2 a='hello' b='my' c='friend'/>
Pass variables in object
const Component3 = ({ a, b, c }) => <div>{a}, {b} dear {c}!</div>
const userProps = { a: 'hello', b: 'my', c: 'friend' }
<Component3 {...userProps}/>
Destructure props inside component That is my favorite way.
const Component4 = (props) => {
const { a, b, c } = props
return <div>{a}, {b} dear {c}!</div>
}
<Component4 a='hello' b='my' c='friend'/>
Pass all props Sometimes we need to pass tons of props from a component to a component. That can create a mess. We can pass all of them at ones using spread operator ... at receiving component. The drawback is that we can not choose specific props we are forwarding, only the whole scope.
function Component5(props1) {
return <Child {...props1} d={3} />;
}
function Child(props2) {
return <>{`${props2.a}, ${props2.b} ${props2.c} ${props2.d} times`}</>
}
<Component5 a="hello" b="my" c="friend" />
Pass rest of the props
const RoundedButton = ({ datatestid, shadow, content, children, ...restProps }) => {
return (
<Button
variant='contained'
data-testid={datatestid}
{...restProps}
>
{content}
{children}
</Button>
)
}