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;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter