SkullDev SkullDev - 2 months ago 12
React JSX Question

Why won't my React Component render multiple times?

I am brushing up on some React but I am having an issue with multiple renders.

I have a List component, it accepts an array of "content" and builds a list from it.

I want it to render the same list of the same content 3-4 times, as you can see below.

However, it actually only renders ONE of these lists...

Why won't it do what I want it to though?

I tried using a loop and adding a different key prop on each (the value of i), etc but to no luck and most articles I have read are quite convoluted and useless.

Here is my current code:



//main.jsx
const React = require("react");
const ReactDOM = require("react-dom");
const List = require("./components/List.jsx");
const textNodes = [{
id: 1,
text: "ok"
}, {
id: 2,
text: "yep"
}, {
id: 3,
text: "aye"
}, {
id: 4,
text: "hey bro"
}];

ReactDOM.render( < List content = {
textNodes
}
/>, document.getElementById("stage"));
ReactDOM.render(
<List content={textNodes}/ > , document.getElementById("stage"));
ReactDOM.render( < List content = {
textNodes
}
/>, document.getElementById("stage"));
ReactDOM.render(
<List content={textNodes}/ > , document.getElementById("stage"));

//List.jsx
const React = require("react");
const ListItem = require("./ListItem.jsx");

const List = React.createClass({
render: function() {
let listItems = this.props.content.map((item) => < ListItem key = {
item.id
}
itemText = {
item.text
}
/>);
return (
<ul>
{listItems}
</ul >
)
}
});

module.exports = List;

//ListItem.jsx
const React = require("react");
const ListItem = React.createClass({
render: function() {
return ( < li >
< h4 > {
this.props.itemText
} < /h4>
</li >
)
}
});

module.exports = ListItem;




Answer

It's because you're rendering the same content into the same div multiple times - each time you render it, you overwrite the previous one.

Instead of doing this:

ReactDOM.render(<List content={textNodes} />, document.getElementById("stage"));

four times, do this:

ReactDOM.render(
    <div>
        <List content={textNodes} />
        <List content={textNodes} />
        <List content={textNodes} />
        <List content={textNodes} />
    </div>,
    document.getElementById('stage')
);
Comments