Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  188] [ 5]  / answers: 1 / hits: 73533  / 7 Years ago, thu, october 26, 2017, 12:00:00

I recently started working with react and I am facing a bit of an issue.



Currently I have the following piece of code



<div className=col-md-4><h4>ML</h4>
{
game.lines.map(function (lineGroup) {
return (
<div className=row>
<div className=col-md-1>
{lineGroup.Pay}
</div>
<div className=col-md-3>
<strong>{getLineInfo(lineGroup.HomeInfo)}</strong>
</div>
<div className=col-md-3>
<strong>{getLineInfo(lineGroup.Score)}</strong>
</div>
<div className=col-md-3>
<strong>{getLineInfo(lineGroup.AwayInfo)}</strong>
</div>
</div>
)
})
}




This sits in my render() function.



However I have this exact same piece of code copy/pasted 5 more times with only minor changes.
I wish to extract it to a function, but I am not sure how would I do this.



Where should I place the function ? -Inside the render() method?



What should I return from it? - A string that contains the html and variables in {} placeholders?



Do I simply call it within the html?


More From » html

 Answers
7

Create function like this :



function gameLines(game) {
return game.lines.map(function (lineGroup) {
return (
<div className=row>
<div className=col-md-1>
{lineGroup.Pay}
</div>
<div className=col-md-3>
<strong>{this.getLineInfo(lineGroup.HomeInfo)}</strong>
</div>
<div className=col-md-3>
<strong>{this.getLineInfo(lineGroup.Score)}</strong>
</div>
<div className=col-md-3>
<strong>{this.getLineInfo(lineGroup.AwayInfo)}</strong>
</div>
</div>
)
})
}


Use like this :



<div className=col-md-4><h4>ML</h4>
{ this.gameLines(game) }
</div>


Dont forget to bind the functions



constructor() {
...
this.gameLines = this.gameLines.bind(this);
this.getLineInfo = this.getLineInfo.bind(this);
}

[#56104] Tuesday, October 24, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 3 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;