What is the difference between usage of
<Component key={1} /> (1)
and
<Component key=1 /> (2)
what is the wrong way to pass number prop here ?
is parser make some logic there before to pass it to the component in the first point ?
CodePudding user response:
Short Answer: The Correct Way to Pass Props/Keys
if you are passing a string you can pass it as:
<Component someProp="123" />
In this case, the prop you are using is key
which is expecting a string,
You should either pass it as:
<Component someProp="123" />
or if it is a variable:
const someKey = 1;
const component = (<Component someProp={someProp.toString()} />)
What happens when the app is built
is parser make some logic there before to pass it to the component in the first point ?
key=1
would give you errors like
JSX value should be either an expression or a quoted JSX text.
and not render properly if at all.
keys will always be converted to strings
Keys are expect to be strings or a type that can be converted to a string. Looking at the react code you will see that there is a function testStringCoercion that will check if the value is a string or can be converted to a string.
Summary
You should pass your keys as a string. If you to not pass it as a string, it will still convert it to a string if possible or it will throw an error.
more on using keys: https://reactjs.org/docs/lists-and-keys.html#basic-list-component
more on using props: https://reactjs.org/docs/components-and-props.html