Answer the question
In order to leave comments, you need to log in
Why does a React component not work in one case and work in another?
class Contact extends React.Component {
constructor(props) {
super(props);
this.state = { name: props.name, value: props.value };
}
render() {
return <div>
<p>{this.state.name}: {this.state.value}</p>
</div>;
}
}
class ContactList extends React.Component {
constructor(props) {
super(props);
this.state = { contacts: props.contacts };
}
render() {
return <div>
{
this.state.contacts.map(function (c) {
return <Contact key={c.name.toString()} name={c.name} value={c.value} />
})
}
</div>;
}
}
function ContactListTwo(props) {
const contacts = props.contacts.map((c) =>
<Contact key={c.name.toString()} name={c.name} value={c.value} />
);
return (
<div>
{contacts}
</div>
);
}
class Root extends React.Component {
constructor(props) {
super(props);
this.state = { contacts: [] };
}
loadData() {
var xhr = new XMLHttpRequest();
xhr.open("get", this.props.apiUrl, true);
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
this.setState({ contacts: data.contacts });
}.bind(this);
xhr.send();
}
componentDidMount() {
this.loadData();
}
render() {
return <div>
<ContactList contacts={this.state.contacts} />
<ContactListTwo contacts={this.state.contacts} />
</div>;
}
}
ReactDOM.render(
<Root apiUrl="/api/contacts" />,
document.getElementById("content")
);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question