alexs333
alexs333

Reputation: 12593

React - dynamic properties from strings

In my test suit, I am trying to generate components with props dynamically, so I will end up with components like so:

<Button primary />
<Button secondary />

Currently, I am a bit stuck:

  [
    'primary',
    'secondary'
  ].forEach((buttonType) => {
    it(`should render the '${buttonType}' button`, () => {
      const button = mount(<Button {...buttonType}>Click me</Button>); // incorrect - will not work
      // rest of the test omitted
    });
  });

Any help would be appreciated.

Upvotes: 1

Views: 366

Answers (2)

Chris
Chris

Reputation: 59541

You cannot map through an array of strings an apply those as boolean props the way you're doing it. Try instead iterating through a map that has each of your button types as keys with true values.

class MyApp extends React.Component {
  render() {
  let arr = [{primary: true}, {secondary: true}]
    return (
      <div>
        {arr.map(buttonType => <Button {...buttonType} />)}
      </div>
    );
  }
}

const Button = (props) => {
  if(props.primary) return <button className="primary">Primary</button>;
  if(props.secondary) return <button className="secondary">Secondary</button>;
  return null;
}

ReactDOM.render(<MyApp />, document.getElementById("app"));
.primary {
  background: orange;
}

.secondary {
  background: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 0

nbkhope
nbkhope

Reputation: 7474

You should replace cardType with buttonType in your function parameter given to forEach.

Then, you should use the following inside the test:

const dynamicProps = { [buttonType]: true };
<Button {...dynamicProps} />

Some elements have been omitted but you get the idea. When you pass a prop without an explicit definition, you actually mean someProp={true}, so in the above case you have to use the primary or whatever as the property of an object, with a value of true.

Upvotes: 1

Related Questions