Florian Bienefelt Florian Bienefelt - 24 days ago 8
React JSX Question

Pass props to a mapped array of different components

I have an array of imported React components with different names, and I'd like to iterate over them and pass the same props to each of them, but I can't find a way to do this properly.

Here's what I have in a form of pseudocode:

const myArray = [
<Component1 />,
<Component2 />,
<Component3 />,
];

render() {
return(
<div>
{myArray.map( ComponentX => {ComponentX} )} // pass the same props into these components?
</div>
);
}

Answer

Don't use JSX inside the array and you should be good:

class Component1 extends React.Component {
  render() {
    return <div>{this.props.prop}</div>;
  }
}

class Component2 extends React.Component {
  render() {
    return <div>{this.props.prop}</div>;
  }
}

const myArray = [
  Component1,
  Component2,
];

class App extends React.Component {
  render() {
    return (
      <div>
        {myArray.map(ComponentX => <ComponentX prop="Hello World!" /> )}
      </div>
    );
  }
}


ReactDOM.render(<App/>, document.getElementById('View'));
<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="View"></div>