How to pass multiple key and their HTML tag attributes in React

Viewed 202

I have an a-tag looking like this

<a href={ item.htmlReportUrl } target="_blank" rel="noopener noreferrer">
{item.htmlReportText}</a>

which gets it's values for the href and the linktext from this

row.htmlReportUrl = res.db[key].htmlReport
row.htmlReportText = 'HTML Report'

My plan was now to in addtion pass

target="_blank" rel="noopener noreferrer"

in the same way. These attributes needs to be set just sometimes. But doing something like this

<a href={ item.finalUrl } { item.htmlReportAttributes } 

isn't working.

Parsing error: Unexpected token, expected "..."

I guess it's added to the href? How can I pass multiple html attributes at once?

3 Answers

Try:

item.htmlReportAttributes["target"] = "_blank";
item.htmlReportAttributes["rel"] = "noopener noreferrer";
<a href={ item.finalUrl } { ...item.htmlReportAttributes } >{item.htmlReportText}</a>

You should define attribute like this

let customAttr= {'target': '_blank','rel':'noopener noreferrer'}

then pass in html tag as below:

<a href={item.finalUrl} {...customAttr} >Link title</a>

If you are checking state for the flag whether you want to use those extra attributes then you could try:

<a href={ item.finalUrl } target={this.state.addExtraAttributes == true ? "_blank" : ""} rel={this.state.addExtraAttributes == true ? "noopener noreferre" : ""} >
Related