Skip to content

Instantly share code, notes, and snippets.

@tonghuikang
Created October 13, 2018 11:26
Show Gist options
  • Save tonghuikang/c997489718f40e124e23434fd6ab1f0a to your computer and use it in GitHub Desktop.
Save tonghuikang/c997489718f40e124e23434fd6ab1f0a to your computer and use it in GitHub Desktop.
React Image Search
<div id="app"></div>
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
image: ''
}
this.search = this.search.bind(this);
}
// Get initial image
componentDidMount() {
this.getImage();
}
// Get search value from input box on submit
search(e) {
e.preventDefault();
this.getImage(this.refs.search.value);
}
// Set image state to the search value
getImage(search = 'nature') {
this.setState({
image: `https://source.unsplash.com/featured/?${search}`
})
}
render() {
const divStyle = {
backgroundImage: `url(${this.state.image})`
}
// Set `search__results` bg image to the image url
return (
<div className="search">
<form onSubmit={this.search}>
<input className="search__input" type="text" placeholder="search..." ref="search" />
</form>
<div style={divStyle} className="search__results">
</div>
</div>
)
}
}
ReactDOM.render(<Search />, document.getElementById("app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script src="https://npmcdn.com/react-dom@15.3.0/dist/react-dom.min.js"></script>
.search {
height: 100%;
width: 100%;
background-color: #333;
position: relative;
&__results {
position: absolute;
top: 0;
width: 100%;
height: 100%;
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
z-index: 1;
}
&__input {
position: absolute;
bottom: 0;
opacity: .75;
padding: .75rem 0 .75rem 1rem;
width: 100%;
border: 0;
font-size: 1.75rem;
background-color: #333;
border-bottom: 2px solid transparent;
z-index: 3;
color: #fff;
letter-spacing: 1px;
outline: 0;
font-weight: 200;
&:hover,
&:focus {
opacity: .9;
border-bottom: 2px solid #53D8FB;
}
&::placeholder {
color: #aaa;
}
}
}
/* Setup */
html,
body,
#app {
height: 100%;
width: 100%;
}
* {
box-sizing: border-box;
transition: 275ms;
}
@tonghuikang
Copy link
Author

Not by me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment