21

I'm about to make the next my page with React and I can't find how to put a configurable attribute set into component, for example:

<ProgressBar active now={current} max={total}/>

I want to add the active attribute inside the ProgressBar only if current == total.

How can I do this?

Is there an easy way to switch between two options active and stripped? Something like this:

<ProgressBar {current==total ? stripped : active} now={current} max={total}/>

except to create a properties object and spread it {...props}

0

1 Answer 1

33

If the component handles false values correctly, just always add the props:

let stripped = this.state.current === this.state.total;

 <ReactBootstrap.ProgressBar
   stripped={stripped}
   active={!stripped}
   now={this.state.current}
   max={this.state.total}
 ?>

If you absolutely have to pass one or the other, you could create an object and spread it into the element:

let props = {
  [this.state.current === this.state.total ? 'stripped' : 'active']: true,
  now: this.state.current,
  max: this.state.total,
};

<ReactBootstrap.ProgressBar {...props} />
6
  • 1
    Hmm. I didn't know that active=false has the same meaning as the non-existing attribute. Thanks. And thanks for {...props}
    – zamuka
    Commented Oct 5, 2015 at 15:07
  • 1
    Well, I assume the component does something like if (this.props.active) { ... }, so whether it's not set or set to false is the same. Commented Oct 5, 2015 at 15:53
  • 1
    some people don't like additional attributes where they aren't needed...why be forced to display the attribute. I'm getting into Jest + Snapshots and this is ridiculously driving me to look for answers in threads like this.
    – beauXjames
    Commented Apr 12, 2019 at 19:01
  • Great example! For the props solution where you just want the property, could use an if, e.g. let props = { ... }; if (needsProp) props['theProp'] = true; ...
    – Nick Bull
    Commented Aug 12, 2020 at 10:40
  • The syntax {...props} is discouraged to use. It's better to use defaultChecked and similar react-analogues in case of built-in html-attributes and to refuse to use them in other cases. See github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/… Commented Apr 26, 2021 at 17:23

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.