I know how to create a list of names using one input text field. How do I create a list of people with an input field of first name and an input field of last name. Thus, how do you create a list of people using multiple input values which consist of last name and first name. How do I do this in react.js?
- John Carter
- Adam West
- Mark Hamill
- Stan Lee
- Peter Parker
- Clark Kent
Right now, I only now how to create a list like the following using only one input field:
- John
- Adam
- Mark
- Stan
- Peter
- Clark
The dots before each name is not necessary at this point.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function PostButton(props){
var style = {
width:24,
height:24
}
return (
<button style = {style} onClick = { () => props.handleClick()}>{props.label}</button>
)
}
function PostText(props){
var style = {
border:"1px solid black",
width: props.width
}
return (
<div style = {style}>{props.text}</div>
)
}
function Post(props){
var style = {
display:"flex"
}
return (
<div style = {style}>
<PostButton label = "x" handleClick = {props.removeItem}/>
<PostTextFirstName text = {props.firstName} width = "200"/>
<PostTextLastName text = {props.lastName} width = "200" />
</div>
)
}
function PostList(props){
return (
<ol>
{
props.postList.map((item,index) =>
<Post key = {index}
firstName = {item.firstName}
lastName = {item.lastName}
removeItem = {() => props.removeItem(index)}
/>
)
}
</ol>
)
}
class App extends React.Component{
constructor(props){
super(props)
this.state = {value:"", items : []}
}
handleChange(event){
this.setState({value:event.target.value})
console.log(this.state.value)
}
addItem()
{
var itemsCopy = this.state.items.slice()
var truncatedString = this.state.value.substring(0,20);
itemsCopy.push({"firstName":truncatedString})
this.setState({items:itemsCopy,value:""})
}
removeItem(index)
{
var itemsCopy = this.state.items.slice()
itemsCopy.splice(index,1);
this.setState({items:itemsCopy})
}
render(){
return (
<div>
<div>First Name</div>
<input value = {this.state.value} onChange = {this.handleChange.bind(this)}/>
<div>Last Name</div>
<input value = {this.state.value} onChange = {this.handleChange.bind(this)}/>
<button onClick = { () => this.addItem()}>Submit</button>
<PostList postList = {this.state.items}
removeItem = {this.removeItem.bind(this)}
/>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById("root")
)