Skip to content

Instantly share code, notes, and snippets.

@jmbejar
Last active December 20, 2017 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbejar/d5f73c0fa0873b00db7d51b7f51d993e to your computer and use it in GitHub Desktop.
Save jmbejar/d5f73c0fa0873b00db7d51b7f51d993e to your computer and use it in GitHub Desktop.
Code example 2 in "Unopinionated comparison of Glimmer and React"
import Component, { tracked } from '@glimmer/component';
const animals = ["Cat", "Dog", "Rabbit"];
export default class extends Component {
@tracked randomAnimals = [];
setRandomAnimal() {
const animal = animals[Math.floor(Math.random() * 3)];
this.randomAnimals = this.randomAnimals.concat(animal);
}
}
import React, { Fragment } from "react";
const animals = ["Cat", "Dog", "Rabbit"];
class RandomAnimal extends React.Component {
constructor() {
super();
this.state = { animals: [] };
this.setRandomAnimal = this.setRandomAnimal.bind(this);
}
setRandomAnimal() {
const animal = animals[Math.floor(Math.random() * 3)];
this.setState((prevState) => (
{ animals: prevState.animals.concat(animal) }
));
}
render() {
const renderedAnimals = this.state.animals.map((animal, index) =>
<li key={index}>{animal}</li>
);
return (
<Fragment>
<button onClick={this.setRandomAnimal}>Set Random Animal</button>
<ul>{ renderedAnimals }</ul>
</Fragment>
);
}
}
<button onclick={{action setRandomAnimal}}>Set Random Animal</button>
<ul>
{{#each randomAnimals key="@index" as |animal| }}
<li>{{animal}}</li>
{{/each}}
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment