Home > Software engineering >  React keys for non-list elements?
React keys for non-list elements?

Time:09-08

If I have some elements to render in a row, e.g.:

<>
  <div className="foo">a</div>
  <p>b</p>
  <button>some button</button>
  <CustomElement myAttr="attr" />
</>

Do I need to add keys for these elements? If not, how is React going to handle the following condition:

<>
  {someCondition && <div className="foo">a</div>}
  <p>b</p>
  <button>some button</button>
  <CustomElement myAttr="attr" />
</>

Assuming that someCondition will be false at first and true after some event, will it cause a re-render on its siblings <p>, <button> and CustomElement?

Or is React simply adding keys automatically for these elements? Thanks!


EDIT: In the second snippet the <div /> element should only show if someCondition is true. All the other three elements should always be shown.

What I actually wanted to ask is that without manually keying the elements, how it React going to know if one element is the same as the other when updating? I'm aware that in the docs it says keying tells that the element is an already existed element.

So I wander that if not giving React keys on normal non-list elements, will React know if they are the same by automatically assigning them a key? Or does React have a special technique to prevent rerenders on normal elements?

CodePudding user response:

I think this is exatly what u want.

<>
    { someCondition ? <div className="foo">a</div> : ''}
    <p>b</p>
    <button>some button</button>
    <CustomElement myAttr="attr" /> 
</>

CodePudding user response:

You can use if-else short. The first if someCondition = false we render className="foo" else <p>, <button>, CustomElement

return (
<>
  { !someCondition ? 
    (<div className="foo">a</div>)
    : '' 
  }
  <p>b</p>
  <button>some button</button>
  <CustomElement myAttr="attr" />
</>
)
  • Related