Reputation: 1126
I'm really new to reactjs and I was looking for a simple way to change the color of a button depending on states. Basically I'm using reactstrap and I have a button, I want its color to be "secondary", "danger" or "primary" the Button tag works that way :
<Button color={String} />
I want to use a function to put a String in there. basically here is a small function :
buttonClassName(radioId) {
if (this.state.whatevs.valid === false)
return "danger";
if (this.state.whatevs.value === radioId)
return "primary";
return "secondary;
}
here is how I want to use it :
<Button outline color={() => this.buttonClassName(1)}>blah blah1</Button>
<Button outline color={() => this.buttonClassName(2)}>blah blah2</Button>
<Button outline color={() => this.buttonClassName(3)}>blah blah3</Button>
and so on for more buttons, problem is, react logically barks at me because :
Warning: Failed prop type: Invalid prop `color` of type `function` supplied to `Button`, expected `string`.
I agree with it, but how can I make that string change without passing a function, do I have to make state out of it, it seems so boringly circumvoluted. When I only had two states, I could just do something like that :
<Button outline color={(whatevs.valid === false)?"danger":"secondary"}>blah blah1</Button>
and that's not really a string either, but it worked.
Upvotes: 1
Views: 943
Reputation: 59491
You can most definetly use a function to return a string. The problem with your implementation is that you were passing a whole function by reference rather than the result of a function.
Just do this simple fix below. This will execute the function and return the desired string to the <Button>
component.
<Button outline color={this.buttonClassName(1)}>blah blah1</Button>
<Button outline color={this.buttonClassName(2)}>blah blah2</Button>
<Button outline color={this.buttonClassName(3)}>blah blah3</Button>
Upvotes: 1