Answer the question
In order to leave comments, you need to log in
How to pass a function to make onclick work in react?
There are two components, one App, where I render shapes using the second one. There are 3 figures, and when you click on any figure, you need to display it higher in a separate div, click on the figure - it is displayed endlessly. What to add to Figure so that it starts working correctly?
export default class Figure extends React.Component {
render(props) {
return <div onClick={this.props.change} className={this.props.type} />
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
figure: [],
index: 0,
}
this.change = this.change.bind(this);
};
change(type){
const figures = this.state.figure
figures.push(type)
this.setState({figure: figures})
};
render() {
return (
<div className="app">
<div>{this.state.figure}</div>
<div className="fig-container">{this.state.figure.map((figureType, i) => <Figure type={figureType} key={i}/> )}</div>
<div className="figures">
<Figure type="circle"/>
<Figure type="square"/>
<Figure type="triangle"/>
</div>
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
const Figure = props => (
<div onClick={props.onClick} className={props.type}></div>
);
class App extends React.Component {
state = {
types: [ 'circle', 'square', 'triangle' ],
figures: [],
}
add(type) {
this.setState(({ figures }) => ({
figures: [ ...figures, type ],
}));
}
render() {
return (
<div>
<div>
{this.state.types.map(n => <Figure type={n} onClick={() => this.add(n)} />)}
</div>
<div>
{this.state.figures.map(n => <Figure type={n} />)}
</div>
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question