24
loading...
This website collects cookies to deliver better user experience
const textAreaStyles = {
width: 235,
margin: 5
};
class MyToDoList extends React.Component {
constructor(props) {
super(props);
// Change code below this line
// Change code above this line
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit() {
const itemsArray = this.state.userInput.split(',');
this.setState({
toDoList: itemsArray
});
}
handleChange(e) {
this.setState({
userInput: e.target.value
});
}
render() {
const items = null; // Change this line
return (
<div>
<textarea
onChange={this.handleChange}
value={this.state.userInput}
style={textAreaStyles}
placeholder='Separate Items With Commas'
/>
<br />
<button onClick={this.handleSubmit}>Create List</button>
<h1>My "To Do" List:</h1>
<ul>{items}</ul>
</div>
);
}
}
textarea
and a button
, along with a couple of methods that track their states, but nothing is rendered to the page yet.All freeCodeCamp wants us to do is inside the constructor, create a this.state
object and define two states: userInput
should be initialized as an empty string, and toDoList
should be initialized as an empty array. Next, in the render method map over the toDoList
array stored in the component's internal state and dynamically render a li for each item.
Answer:
class MyToDoList extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: "",
toDoList: []
}
render() {
const items = this.state.toDoList.map(l => <li>{l}</li>);
map
is filter
, which filters the contents of an array based on a condition, then returns a new array.
*Code:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [
{
username: 'Jeff',
online: true
},
{
username: 'Alan',
online: false
},
{
username: 'Mary',
online: true
},
{
username: 'Jim',
online: false
},
{
username: 'Sara',
online: true
},
{
username: 'Laura',
online: true
}
]
};
}
render() {
const usersOnline = null; // Change this line
const renderOnline = null; // Change this line
return (
<div>
<h1>Current Online Users:</h1>
<ul>{renderOnline}</ul>
</div>
);
}
}
MyComponent
's state is initialized with an array of users. Some users are online and some aren't. Let's Filter the array so you see only the users who are online. Then, in the renderOnline
variable, let's map
over the filtered array, and return a li element for each user that contains the text of their username. We'll also include a unique key
render() {
const usersOnline = this.state.users.filter(user => user.online);
const renderOnline = usersOnline.map(online => <li key = {online.username}>{online.username}</li>);