Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React's props with the same name as their value

Tags:

reactjs

Can we pass props to a component that has the same name and value implicitly?

Example: Let's say that I have a variable called x: const x = 1; and I have a component that has a prop called x. Can I pass it this variable as value implicitly? like that: <div x/>?

like image 670
Pistolpete . Avatar asked Jul 03 '18 06:07

Pistolpete .


People also ask

Why should you avoid copying the values of props into a component's state?

Anti-pattern: Unconditionally copying props to state Because of this, it has always been unsafe to unconditionally override state using either of these lifecycles. Doing so will cause state updates to be lost.

How can you pass a boolean value true as the prop named?

There is no need to write that a prop is equal to true. Instead, you can just include the prop value, and it will be given the boolean value true when you use it in a component to which you pass it.

Can I rename props in React?

Press F2 and then type the new desired name and press Enter. All usages of the symbol will be renamed, across files.

Does React pass props by reference?

Short answer: props are passed by reference. The reason it can be confusing: if you change the parent's state by hand (bad practice!), the object will change in the child component, too. But won't trigger re-render! (The child component won't "know" that its props has changed.)


1 Answers

Booleans can be passed implicitly to the component as @Ajay also pointed out in comments, like

<div x /> 

which is basically equivalent to

<div x={true} /> 

However, if your variable is something other than a boolean, then you need to write it like

<div x={x} /> 

Or if you have a number of such props, you can form an object like

const cmpProps = {    x,    y,    foo,    bar } 

and pass them using Spread attributes like

<Comp {...cmpProps} /> 
like image 199
Shubham Khatri Avatar answered Sep 21 '22 08:09

Shubham Khatri