Skip to content

Exercise React Components State Props

sergio edited this page Jan 25, 2021 · 2 revisions

//fetch library without backend? import fetchMock from 'fetch-mock'; import { getAll, getByType } from './data/pets'; import 'whatwg-fetch';

fetchMock.get('/api/pets', getAll()); fetchMock.get('/api/pets?type=cat', getByType('cat')); fetchMock.get('/api/pets?type=dog', getByType('dog')); fetchMock.get('/api/pets?type=micropig', getByType('micropig'));

export default fetchMock;

//index import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; import './fetch-setup';

ReactDOM.render(, document.getElementById('root'));

[data](https://github.com/learn-co-students/react-props-and-state-lab-online-web-sp-000/blob/solution/src/data/pets.js)

//App import React from 'react';

import Filters from './Filters'; import PetBrowser from './PetBrowser';

class App extends React.Component { constructor() { super();

this.state = {
  pets: [],
  filters: {
    type: 'all'
  }
};

}

fetchPets = () => { let endpoint = '/api/pets';

if (this.state.filters.type !== 'all') {
  endpoint += `?type=${this.state.filters.type}`;
}

fetch(endpoint)
  .then(res => res.json())
  .then(pets => this.setState({ pets: pets }));

};

onChangeType = ({ target: { value } }) => { this.setState({ filters: { ...this.state.filters, type: value } }); };

onAdoptPet = petId => { const pets = this.state.pets.map(p => { return p.id === petId ? { ...p, isAdopted: true } : p; }); this.setState({ pets: pets }); };

render() { return (

React Animal Shelter

); } }

export default App;

//Filters import React from 'react';

class Filters extends React.Component { render() { return (

Animal type

All Cats Dogs Micropigs
    <div className="field">
      <button
        onClick={this.props.onFindPetsClick}
        className="ui secondary button">
        Find pets
      </button>
    </div>
  </div>
);

} }

export default Filters;

//PetBrowser import React from 'react';

import Pet from './Pet';

class PetBrowser extends React.Component { render() { const petCards = this.props.pets.map(pet => ( ));

return <div className="ui cards">{petCards}</div>;

} }

export default PetBrowser;

//Pet import React from 'react';

class Pet extends React.Component { render() { return (

{this.props.pet.name}{' '} {this.props.pet.gender === 'female' ? '♀' : '♂'}
{this.props.pet.type}

Age: {this.props.pet.age}

Weight: {this.props.pet.weight}

{this.props.pet.isAdopted ? ( Already adopted ) : ( <button onClick={() => this.props.onAdoptPet(this.props.pet.id)} className="ui primary button"> Adopt pet )}
); } }

export default Pet;

Clone this wiki locally