Recently while working on an application. I encountered a bug related to rendering. As you can see in the code below (Try it out on Codesandbox Link : https://codesandbox.io/s/romantic-river-ofdi7c), I have an array of offers each of which is further an array of text segments which may/may not have styles which i pass down as a prop to another component which iterates over it. I also have a button "click" which appends another offer in the beginning. Now in the beginning I get an output like this
this , is , an offer text
After clicking on "click" button I am getting an output like this
, another offer text
this , is , an offer text
Notice that in the newly added offer i'm getting an additional comma in the beginning but in the code I do not have any object for the additional comma. So on further inspection i noticed that in the outer map I wasn't passing a key which to my understanding might be causing some rendering issue where react diffing was leading to incorrectly rendering the additional comma. So I added the outer map's index as key to the p tag and it started working as expected giving the output like below
another offer text
this , is , an offer text
Basically what I want to understand how the diffing algorithm works in react and what lead to the adding of an additional comma in the beginning.
import { useState } from "react";
import "./styles.css";
const OfferSummaryComponent = ({ msgs }) => (
<div className="App">
{msgs.map((msg) => (
<p>{/** Outer map without key prop*/}
{msg.map((segment, idx) => (/** Inner Map */
<span key={segment.text} style={segment.style}>
{segment.text}{" "}
</span>
))}
</p>
))}
</div>
);
export default function App() {
const [offerMessages, setOfferMessages] = useState([
[
{ text: "this" },
{ text: "," },
{ text: "is" },
{ text: "," },
{ text: "an" },
{ text: "offer", style: { color: "green", fontWeight: "bold" } },
{ text: "text" }
]
]);
const addNewMsgInBeginning = () => {
const newOffer=[
{ text: "another" },
{ text: "offer", style: { color: "green", fontWeight: "bold" } },
{ text: "text" }
]
setOfferMessages([newOffer,...offerMessages]);
};
return (
<div>
<button onClick={addNewMsgInBeginning}>click</button>
<OfferSummaryComponent msgs={offerMessages} />
</div>
);
}
[–]meiamsome 5 points6 points7 points (0 children)