Add random element to array : React
Thu Jun 24 2021 16:12:14 GMT+0000 (Coordinated Universal Time)
Saved by
@hisam
#array
#destructuring
#javasc
#react.js
import React, { Component } from "react";
class IconList extends Component {
static defaultProps = {
options: [
"angry",
"anchor",
"archive",
"at",
"archway",
"baby",
"bell",
"bolt",
"bone",
"car",
"city",
"cloud",
"couch"
]
};
constructor(props) {
super(props);
this.state = { icons: ["bone", "cloud"] };
this.addIcon = this.addIcon.bind(this);
}
//DON'T DO THIS!!!!
// addIcon() {
// let idx = Math.floor(Math.random() * this.props.options.length);
// let newIcon = this.props.options[idx];
// let icons = this.state.icons;
// icons.push(newIcon);
// this.setState({ icons: icons });
// }
addIcon() {
// get random index
let idx = Math.floor(Math.random() * this.props.options.length);
// get new element
let newIcon = this.props.options[idx];
// update the state of the icons array (spread icons into new array, add new icon to it)
this.setState({ icons: [...this.state.icons, newIcon] });
}
render() {
// render newly mapped icons array
const icons = this.state.icons.map(i => <i className={`fas fa-${i}`} />);
return (
<div>
<h1>Icons: {icons}</h1>
<button onClick={this.addIcon}>Add New Icon</button>
</div>
);
}
}
export default IconList;
content_copyCOPY
Only use pure functions when working with mutable types in react
Comments