Cᴀʟʟᴏᴅᴀᴄɪᴛʏ Cᴀʟʟᴏᴅᴀᴄɪᴛʏ - 1 year ago 121
React JSX Question

Update React component by key

I have a React app that has a tabbed interface of open files. The open files array looks like this:

{ name: 'file1', path: '/path/to/file1', fileContents: '...' },
{ name: 'file2', path: '/path/to/file2', fileContents: '...' },
{ ... }

Which are rendered into
's like so:

render() {
return this.state.files.map((file, i) => {
return <div key={`tab--${file.path}`}> ... </div>;

When my app renames the file, it re-renders the entire tab (since the
prop is now different due to the path update, React thinks it's a different component altogether and disposes of the previous element).

When rename "file2" to "file3", I would like my app to update the
without re-rendering the component at all - so just updating the
prop on the component.

Is there any way to find components by their
and subsequently update that

Answer Source

Keys shouldn't be used to access components. They're just used to let react keep track of the components within that scope. I'd just use i for your key (so that React doesn't lose track of the components) and use ref (<div key={i} ref={(f) => this[file.name] = f} />) to access the components themselves (via this[file.name]).

You'll probably need to do some cleanup with this[file.name] still pointing to objects when file.name has been changed to something else, but this will get you closer to what you need, I think.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download