Reputation: 433
I'm trying to render several different components and passing it's props via a mapping. componentInfo
contains an array of the information that's being passed.
displayComponent() {
this.state.componentInfo.map(info => {
return (
<SomeComponent info={info}/>
)
})
}
In my React component, I want these components generated based off a button click with fires the displayComponent
function.
render() {
return (
<div style={{ marginLeft: 20 }}>
<RaisedButton label="DISPLAY" onClick={this.displayComponent} />
</div>
}
However, I'm unable to display the components. Why is this?
Upvotes: 1
Views: 28
Reputation: 31024
You are not rendering displayComponent
, just invoking it on a click event.
In the current setup of your code i find it hard to achieve what you are after, I would separate the objects inside the state:
state = {
showComponents: false,
componentInfo: ['info 1', 'info 2', 'info 3'],
components: []
}
Then you can populate the components array and render it conditionally.
Running example:
const SomeComponent = ({ info }) => <div>{info}</div>;
class App extends React.Component {
state = {
showComponents: false,
componentInfo: ['info 1', 'info 2', 'info 3'],
components: []
}
setComponents = () => {
this.setState(state => {
const { componentInfo } = state;
const nextComponents = componentInfo.map(info => <SomeComponent info={info} />);
return {
components: nextComponents,
showComponents: true
}
});
}
render() {
const { showComponents, components } = this.state;
return (
<div>
<button onClick={this.setComponents}>Set Components</button>
<hr/>
{showComponents && components}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<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="root"></div>
Upvotes: 1