Skip to content

Instantly share code, notes, and snippets.

@ChaseH88
Created February 28, 2019 11:58
Show Gist options
  • Save ChaseH88/28db59198b8935f80faf69280cb37cbc to your computer and use it in GitHub Desktop.
Save ChaseH88/28db59198b8935f80faf69280cb37cbc to your computer and use it in GitHub Desktop.
React On Key Press
<div id="root"></div>
//------------Component------------
class App extends React.Component {
// --State--
state = {
user: {
name: "Type Here!",
age: 26
},
image: {
url: "https://pixabay.com/get/e833b30f2cf1033ed1584d05fb1d4e97e07ee3d21cac104491f7c07ea0eebcbd_340.jpg"
}
};
onKeyPress = (e) => {
this.setState({
user: {
name: e.target.value
}
})
}
onResetInput = (e) => {
this.setState({
user: {
name: ""
}
})
}
// --Events--
render(){
return (
<div id="app">
<p>Type Something Into the Textbox!</p>
<input onChange={this.onKeyPress} value={this.state.user.name}/>
<p><button onClick={this.onResetInput}>Start Over</button></p>
<div className="container">
<h1>{this.state.user.name}</h1>
<h2>{this.state.user.name}</h2>
<h3>{this.state.user.name}</h3>
<h4>{this.state.user.name}</h4>
<h5>{this.state.user.name}</h5>
<h6>{this.state.user.name}</h6>
</div>
</div>
)
}
}
// React DOM Render Method
ReactDOM.render(
<App />, document.querySelector("#root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0/umd/react-dom.production.min.js"></script>
h1, h2, h3, h4, h5, h6 {margin: 5px 0;}
input {display: block; width: 75%; margin: 20px auto 0; padding: 5px 10px; border-radius: 6px; border: 1px solid #6b6b6b }
p {text-align: center; font-size: 24px; margin: 10px 0 0; padding: 0;}
.container {margin: 1vw; padding: 2vw; background: #f3f3f3; border: 1px solid #ddd}
button {padding: 5px 30px; font-size: 16px; transition: all 100ms ease; position: relative; top: 0;}
button:hover, button:focus {cursor: pointer;}
button:active {top: 2px; transform: scale(.975)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment