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;
}
Top comments (0)