The react docs say:
... In the current implementation, you can express the fact that a subtree has been moved amongst its siblings, but you cannot tell that it has moved somewhere else. The algorithm will rerender that full subtree.
So the key parameter only matches children in the original tree with children in the subsequent tree for a single parent.
Is there a way to tell React a child has moved to another parent? Or another solution for tracking children for CSS transitions?
For example:
If I use:
const [state, setState] = useState({ title1: ["e1", "e2", "e4"], title2: ["e3"] })
To return a list of lists to a render function:
return Object.keys(state).map((title) => (
<div key={title}>
{state[title].map((e) => (
<div key={e}>{e}</div>
))}
</div>
));
But then decide to move "e4" to title2 with an onClick somewhere:
<button onClick = {onClick("e4","title2")}>Move E4 to Title2</button>
Using this onClick helper function:
const onClick = (elem, newtitle) => () =>
setState((s) => {
const titles = Object.keys(s);
const title = titles.filter((t) => s[t].includes(elem))[0]; //find which title contains the element
return {
...s,
[title]: s[title].filter((e) => e !== elem), // remove element from old title list
[newTitle]: s[newTitle].concat(elem), //add it to new title list
};
});
This renders the new state, where e1, e2, e3, and their parents are all tracked using the key property, but e4 is rendered as a new element in title2.
I don't even know where to start with this, or if it is even possible since the docs say it isn't possible out of the box.
P.S I am wanting to do this for CSS transitions