I have a button for rendering new components (actually charts, i have simplified the example to only show text) which adds a text to the page the first time it's clicked, but won't add any new text-objects to the page with further clicks.
I've tested to see if the function is actually running when I'm pressing it multiple times by making it add elements to an array which it does, so why isn't it rendering new text-objects to the page when clicked multiple times?
I might be missing something fundamental and would be grateful for any explanation.
import React from 'react';
import './App.css';
class NewChart extends React.Component {
render() {
return (
<div>Text</div>
);
}
}
class Button extends React.Component {
render() {
return (
<button {...this.props}>
Add chart
</button>
);
}
}
class ChartApp extends React.Component {
constructor() {
super();
this.state = {
clicked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
clicked: true
});
}
render() {
return (
<div>
<Button onClick={this.handleClick} />
{this.state.clicked ? <NewChart />: null}
</div>
);
}
};
export default React.createClass({
render: function () {
return (
<div>
<ChartApp>
</ChartApp>
</div>
)
}
});
You are presently using a button which sets a single flag to true, and then rendering a component when that flag is true. If you would like to render multiple components, you need some aspect of your state to relate to how many components you want to render, and then render based on that. For example as you mention, if you either use an array or perhaps a counter variable, you could then use either .map
or even a for loop to render multiple components. Right now you're only asking React to conditionally render a single NewChart component.