02.13 React State - Basic form with one input (class components)
adriangheo
Posted on October 24, 2022
src/App.js
import React from 'react';
import './App.css';
import NameForm from './NameFormCls';
class App extends React.Component{
render(){
return (
<div className="App">
<h1>App.js</h1>
<NameForm/>
</div>
);
}
}
export default App;
src/App.css
.App{
background-color: lightskyblue;
padding: 20px 10px;
}
src/NameFormCls.js
import React from "react";
import './NameFormCls.css'
class NameForm extends React.Component {
constructor(){
super();
this.state = {
users: [],
newUserName: ""
}
}
handleUsernameInputChange = (event) => {
this.state.newUserName = event.currentTarget.value;
}
handleFormSubmit = (event) => {
event.preventDefault();
const newUser = {
username: this.state.newUserName
}
this.updateUsersList(newUser)
}
updateUsersList = (newUser) => {
this.setState((prevState) =>{
return {
users: [
...prevState.users,
newUser
]
}
})
}
render() {
return (
<div className="name-form">
<h1>NameFormCls.js</h1>
<h3>User List:</h3>
<div>
<form onSubmit={(event)=>{this.handleFormSubmit(event)}}>
<label htmlFor="username">New Username:</label>
<input type="text" name="username" onChange={(event)=>{this.handleUsernameInputChange(event)}}></input>
<input type="submit" value="Submit form!"></input>
</form>
</div>
<div>
{
this.state.users.map((user, index) => {
return(<div>
<span>{index+1}. </span><span>{user.username}</span><br/>
</div>)
})
}
</div>
</div>
);
}
}
export default NameForm;
src/NameFormCls.css
.name-form{
background-color: lightsalmon;
padding: 10px 10px;
}
π πͺ π
π©
adriangheo
Posted on October 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Mastering React Performance: In-Depth Guide to useCallback and useMemo. π
November 24, 2023
javascript Rewrite styled-components in ReactJS with just 60 lines of JavaScript code
September 29, 2023