Skip to content

Instantly share code, notes, and snippets.

@eunicode
Created November 17, 2017 19:58
Show Gist options
  • Save eunicode/8914efa390699c017fea61a2b7a35715 to your computer and use it in GitHub Desktop.
Save eunicode/8914efa390699c017fea61a2b7a35715 to your computer and use it in GitHub Desktop.
const TYPES = [
{
'Web': 'https://www.google.com/search?q=',
'Images': 'https://www.google.com/search?tbm=isch&q=',
'News': 'https://www.google.com/search?tbm=nws&q=',
'Videos': 'https://www.google.com/search?tbm=vid&q=',
'Maps': 'https://www.google.com/maps/preview?q='
}
]
// Parent component
class GoogleSearch extends Component {
constructor(props) {
super(props);
this.state = {
selected: 'Web',
};
}
handleClick = (type, event) => {
event.preventDefault();
this.setState({selected: type});
}
render() {
return (
<div>
<SearchType
types={Object.keys(TYPES[0])}
selected={this.state.selected}
handleClick={this.handleClick}/>
</div>
)
}
}
// Child component
class SearchType extends React.Component {
render() {
const types = this.props.types;
const spanItems = types.map((type) => // type variable is accessible in handleClick() bc of closure
<span
key={type}
className={this.props.selected === type ? 'is-active' : ''}
onClick={this.props.handleClick.bind(this, type)}>
{type}
</span>
);
return (
<div className='search-type'>
{spanItems}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment