Skip to content

Instantly share code, notes, and snippets.

@cassiozen
Created February 16, 2016 17:53
Show Gist options
  • Save cassiozen/da24faaa75e2afeb2bb6 to your computer and use it in GitHub Desktop.
Save cassiozen/da24faaa75e2afeb2bb6 to your computer and use it in GitHub Desktop.
import React, { Component, PropTypes } from 'react';
import { render } from 'react-dom';
import 'whatwg-fetch';
// Renders a SearchBar and a ContactList
// Passes down filterText state and handleUserInput callback as props
class ContactsApp extends Component {
constructor(){
super();
this.state={
filterText: '',
contacts:[]
};
}
componentDidMount(){
fetch('https://dl.dropboxusercontent.com/s/x3qpx8nt81txuas/contacts.json?dl=1')
.then(response => response.json())
.then(json => {
this.setState({contacts:json})
})
}
handleUserInput(searchTerm){
this.setState({filterText:searchTerm})
}
render(){
return(
<div>
{
this.state.contacts.length === 0? <p>LOADING...</p> : ''
}
<SearchBar filterText={this.state.filterText}
onUserInput={this.handleUserInput.bind(this)} />
<ContactList contacts={this.state.contacts}
filterText={this.state.filterText}/>
</div>
)
}
}
// Pure component that receives 2 props from the parent
// filterText (string) and onUserInput (callback function)
class SearchBar extends Component {
handleChange(event){
this.props.onUserInput(event.target.value)
}
render(){
return <input type="search"
placeholder="search"
value={this.props.filterText}
onChange={this.handleChange.bind(this)} />
}
}
// Pure component that receives both contacts and filterText as props
// The component is responsible for actualy filtering the
// contacts before displaying them.
// It's considered a pure component because given the same
// contacts and filterText props the output will always be the same.
class ContactList extends Component {
render(){
let filteredContacts = this.props.contacts.filter(
(contact) => contact.name.indexOf(this.props.filterText) !== -1
);
return(
<ul>
{filteredContacts.map(
(contact) => <ContactItem key={contact.email}
name={contact.name}
email={contact.email} />
)}
</ul>
)
}
}
class ContactItem extends Component {
render() {
return <li>{this.props.name} - {this.props.email}</li>
}
}
render(<ContactsApp />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment