7

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?

1 Answer 1

16

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.