1

In the code below, {...{key}} seems to be adding unique key indexes to the html tags, which I think is required by React. But how does this syntax work? I'm familiar with spread operator, but not sure how to put all of it together. This link https://reactjs.org/docs/lists-and-keys.html gives examples on key usage, but none use this syntax.

const App = () => {
        const subStrings = testString.split(/(:.*?;)/)
        return (
          <div>
            {
              subStrings.map((s,key) => 
                /(:.*;)/.test(s) ? 
                <mark {...{key}}>{s.slice(1,-1)}</mark> :
                <span {...{key}}>{s}</span>
              )
            }
          </div>
        )
      }
Ravi
  • 3,418
  • 6
  • 35
  • 52
  • 2
    https://reactjs.org/docs/jsx-in-depth.html#spread-attributes – jonrsharpe May 15 '20 at 16:57
  • @jonrsharpe This link and the answer below both pass objects, and they're expanded by spread operator. But in the example above, key is just an int. How does it get expanded? And what's going on with 2 sets of braces? – Ravi May 15 '20 at 17:01
  • 3
    Are you asking about property shorthand? In that case, https://stackoverflow.com/q/34414766/3001761 – jonrsharpe May 15 '20 at 17:02
  • Yes! That's very helpful. I wasn't sure how key would expand without specifying it as an object. – Ravi May 15 '20 at 20:44

1 Answers1

4

The syntax {...{keys}}is usually used to pass dynamic props and is called rest spread syntax

This of it as

const keys = 'xyz';
const props = { keys: keys}; // can also be written as const props = {keys};
...
<mark {...props}>{s.slice(1,-1)}</mark>

However there was really no need of this syntax here and could have been simply written as

<mark key={key}>{s.slice(1,-1)}</mark>
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318