Reputation: 2257
I am trying to rewrite a traditional html/js app in React. I have a React component that I want to build that will be made up of many different spans that are next to each other.
<span id="1">one</span><span id="2">two</span><span id="4">four</span>
These elements will be generated from some state. The state may change in the future and new spans may need to be added or removed. For example, the value 'three' might be introduced in the future and it will need to be placed in between some previously created elements (between 'two' and 'four'). The spans should look like this:
<span id="1">one</span><span id="2">two</span><span id="3">three</span><span id="4">four</span>
My question is, should I totally recreate all of the spans from my state in each call to render() every time a single small state change is made? Or, can I find the new element's neighbor by id and then add the new one next to it (this is how my non-react app works)?
The former seems like it would be a lot of work to add one new span. The latter seems more efficient but I don't know if I can use document.getElementById() or something equivalent and add the new element in the more traditional html/js way.
Also, should I use React 'keys' for these spans?
Upvotes: 0
Views: 740
Reputation: 1941
A very simple example:
const myArr = [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 4, value: 'four' }
]
myArr.map(item => <span key={item.id}>{item.value}</span>)
Now if at some point you would add another object to myArr and sort it accordingly it will appear in the place you gave it by sorting. Only the elements with the keys which are new to the react-virtual-dom will be re-rendered, means the new object added to myArr. The reset will stay from the last render cycle.
So by using unique keys you give react the ability to understand which dynamic elements needs to be created, deleted or updated
Upvotes: 1