Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional attributes in React component?

Tags:

reactjs

I'm new to react and I just wrote some ugly code. Can someone show me the better way to do it? Here's the pseudocode:

let btn;

if(this.props.href && !this.props.onClick && !this.props.dataMsg etc...)
btn = <a href={this.props.href}>{this.props.text}</a>;


else if(!this.props.href && this.props.onClick && !this.props.dataMsg etc...)
btn = <a onClick={this.props.onClick}>{this.props.text}</a>;

etc...

else if(this.props.href && this.props.onClick && !this.props.dataMsg etc...)
btn = <a href={this.props.href} onClick={this.props.onClick}>{this.props.text}</a>;

else if(!this.props.href && this.props.onClick && this.props.dataMsg etc...)
btn = <a onClick={this.props.onClick} data-msg={this.props.dataMsg}>{this.props.text}</a>;

etc...

In other words, I want to set the attributes of the <a> element only if the react component received a props for it. However, not all props of the react component are meant to be an attribute, some of it could be this.props.text which belongs in the innerHTML.

There must be a less verbose way to write what I want?

like image 984
John Avatar asked Oct 08 '16 10:10

John


Video Answer


1 Answers

React will ignore all the attribute which has undefined as its value.

So, you don't need to use if conditions. Instead, you can check for the value attribute and return undefined if you don't get the value.

For Example:

You can write you code as follows,

<a
  href={this.props.href} //returns undefined if href not present in props
  onClick={this.props.onClick && this.props.onClick} //set callback if it is present in the props
  data-msg={this.props.dataMsg} //returns undefined if href not present in props
>
 {this.props.text}
</a>;

Returning undefined to any attributes makes React to ignore those attributes.

Hope it helps!

like image 155
Pranesh Ravi Avatar answered Sep 30 '22 09:09

Pranesh Ravi