Reputation: 3213
I have data like below.
this.state.jsonData = [
{
category: "1",
clientname: "rahul1",
reporthtml: "hello1"
},
{
category : "1",
clientname: "rahul2",
reporthtml: "hello2"
},
{
category : "2",
clientname: "rahul2",
reporthtml: "hello2"
},
{
category : "2",
clientname: "rahul2",
reporthtml: "hello2"
},
{
category : "2",
clientname: "rahul2",
reporthtml: "hello2"
},
];
Now i need to render it in react jsx like below. Not getting to make the if else to show only same category only once
My html:
<div>
<div> Category Name</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
</div>
<div>
<div> Category Name</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
<div>Client Name</div>
<div>Client Html</div>
</div>
{this.state.jsonData.map(function(category,i) {
return <div> category.category</div>// This line will only print once for each category need if else condition
<div>Client Name</div>
<div>Client Html</div> ;
})}
Upvotes: 0
Views: 464
Reputation: 2214
and if you have es6 you can enhance the code like that:
render() {
return <div>
{
this.state.jsonData.map(category => <div>
<div>Category: {category.category}</div>
{
category.categorydata.map(data => <div>
<div>Client: {data.clientname}</div>
<div>Report: {data.reporthtml}</div>
</div>
)
}
</div>
)}
</div>
}
Upvotes: 0
Reputation: 1075925
If I'm inferring what you want properly, you just use a nested map
:
render() {
return <div>
{this.state.jsonData.map(function(category) {
return <div>
<div>Category: {category.category}</div>
{category.categorydata.map(function(data) {
return <div>
<div>Client: {data.clientname}</div>
<div>Report: {data.reporthtml}</div>
</div>;
})}
</div>;
})}
</div>;
}
Live Example:
class Category extends React.Component {
constructor(...args) {
super(...args);
this.state = {};
this.state.jsonData = [{
category: "1",
categorydata: [{
clientname: "rahul1",
reporthtml: "hello1"
}, {
clientname: "rahul2",
reporthtml: "hello2"
}, ]
}, {
category: "2",
categorydata: [{
clientname: "rahul1",
reporthtml: "hello1"
}, {
clientname: "rahul2",
reporthtml: "hello2"
}, ]
}];
}
render() {
return <div>
{this.state.jsonData.map(function(category) {
return <div>
<div>Category: {category.category}</div>
{category.categorydata.map(function(data) {
return <div>
<div>Client: {data.clientname}</div>
<div>Report: {data.reporthtml}</div>
</div>;
})}
</div>;
})}
</div>;
}
};
ReactDOM.render(
<Category />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Upvotes: 1