Skip to content

Instantly share code, notes, and snippets.

@Sammuel09
Created February 7, 2018 12:40
Show Gist options
  • Save Sammuel09/c72bd093eba0b36e8d3926d4a2af8a86 to your computer and use it in GitHub Desktop.
Save Sammuel09/c72bd093eba0b36e8d3926d4a2af8a86 to your computer and use it in GitHub Desktop.
Developers Circle, Facebook - Lagos. React Workshop Day 2. Building an interactive search
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { InputField } from './components/InputField';
class App extends Component {
constructor(props, context) {
super(props, context);
this.state = {
value: '',
dataSource: [
'hello world',
'foo',
'bar',
'hello',
'John',
'foot mat',
'Jane',
'book',
'booked',
'Doe',
'jane doe'
],
results: [],
error: ''
};
}
onChange = (event) => {
const value = event.target.value
this.updateState(value);
}
updateState = (value = '') => {
this.setState({
value: value ? value : '',
results: this.filterDataSource(value),
}, () => this.setState({error: value && this.state.results.length <= 0 && 'No result bro!!'}))
}
filterDataSource = (value) => {
return value ? this.state.dataSource.filter((data) => {
const reg = new RegExp(value, 'gi');
return data.match(reg);
}) : [];
}
render() {
const { value, results, error } = this.state;
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<div className="input-box">
<InputField
onChange={this.onChange}
value={value}
/>
<div className="data-sources">
{
results.map((data, index) => {
return (
<p key={index}>
{index + 1} { data }
</p>
)
})
}
{
error
}
</div>
</div>
</div>
);
}
}
export default App;
export { default as InputField } from './InputField';
import React from 'react';
import PropTypes from 'prop-types';
const InputField = ({ type, value, onChange, onBlur, onFocus, placeHolder }) => {
return (
<div>
<input
type={type}
value={value}
onChange={onChange}
onBlur={onBlur}
onFocus={onFocus}
placeholder={placeHolder}
/>
</div>
)
}
InputField.propTypes = {
type: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onBlur: PropTypes.func,
onFocus: PropTypes.func,
placeholder: PropTypes.string,
};
InputField.defaultProps = {
type: 'text',
value: '',
onChange: () => console.warn('you did not add onChange property')
}
export default InputField;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment