20

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}

zamuka
  • 796
  • 2
  • 9
  • 21

1 Answers1

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} />
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Hmm. I didn't know that **active=false** has the same meaning as the non-existing attribute. Thanks. And thanks for {...props} – zamuka Oct 05 '15 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. – Felix Kling Oct 05 '15 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 Apr 12 '19 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 Aug 12 '20 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 https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md – Ruslan Zhomir Apr 26 '21 at 17:23
  • how about id attriute. if an element don't want to assgin id when not provide – twindai Sep 02 '21 at 01:29