React Example - Real-time search
Part of a tutorialzine article.
by Lio Fleishman
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/react-dom.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
</div>
SCSS
* {
padding: 0;
margin: 0;
}
html {
font: 14px normal Arial, sans-serif;
color: #626771;
background-color: #fff;
}
body {
padding: 60px;
text-align: center;
}
input[type=text] {
text-align: center;
font: inherit;
border: 6px solid #a3d8d6;
padding: 13px 12px;
font-size: 15px;
box-shadow: 0 1px 1px #DDD;
width: 384px;
outline: none;
display: block;
color: #7B8585;
margin: 0 auto 20px;
}
ul {
list-style: none;
display: inline-block;
width: 420px;
text-align: left;
li {
display: block;
padding: 15px 20px;
background-color: #F8F8F8;
color: #7B8585;
margin-bottom: 3px;
position: relative;
transition: 0.3s;
&:hover {
background-color: #d8f2f1;
}
a {
position: absolute;
left: 160px;
font-size: 12px;
line-height: 16px;
color: #969d9d;
}
}
}
JavaScript 1.7
class SearchExample extends React.Component {
constructor(props) {
super(props);
this.state = {
searchString: ''
};
}
handleChange(e) {
this.setState({
searchString: e.target.value
});
}
render() {
var libraries = this.props.items;
var searchString = this.state.searchString.trim().toLowerCase();
if (searchString.length > 0) {
libraries = libraries.filter(function(l, index) {
let objNames = l.name.toLowerCase().match(searchString);
let myKeywords = l.keywords
if (myKeywords) {
return objNames
} else {
for (let i = 0; i < myKeywords.length; i++) {
console.log(myKeywords[i].toLowerCase().match(searchString));
let obj = myKeywords[i].toLowerCase().match(searchString);
for (var key in obj) {
console.log(obj[key])
return obj[key]
}
}
}
});
}
return ( < div >
< input type = "text"
value = {
this.state.searchString
}
onChange = {
this.handleChange.bind(this)
}
placeholder = "Type here" / >
< ul > {
libraries.map(function(l) {
return <li key = {
l.id
} > {
l.name
} < a href = {
l.url
} > {
l.url
} < /a></li >
})
} < /ul> < /div >
)
}
};
var libraries = [
{
id: '01',
name: 'Backbone.js',
url: 'http://documentcloud.github.io/backbone/',
keywords: ['pepper', 'salt', 'oranges', 'lemons']
}, {
id: '02',
name: 'AngularJS',
url: 'https://angularjs.org/',
keywords: ['keyboard', 'mouse', 'screen', 'cable']
}, {
id: '03',
name: 'jQuery',
url: 'http://jquery.com/',
keywords: ['js', 'framework', 'vanilla', 'angular2', 'angular1']
}, {
id: '04',
name: 'Prototype',
url: 'http://www.prototypejs.org/',
...