Answer the question
In order to leave comments, you need to log in
How to display POST data in react?
How to properly render all tweets?
Here's what happened:
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
class Tweet {
render() {
return (
<article>
<a href="#">
<img src="https://vignette.wikia.nocookie.net/animal-jam-clans-1/images/e/ea/4801e9af45ef7170bs8d38edd0e1f1e31--anime-guys-anime-manga.jpg/revision/latest?cb=20171205180246" alt="HUI" />
</a>
</article>
);
}
}
class Capture extends React.Component {
constructor(props) {
super(props);
this.state = {
form: {
username: ''
}
}
this.onFormSubmit = this.onFormSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
onFormSubmit(e) {
e.preventDefault()
axios.post('/', {
username: this.state.form.username
})
.then(({data: tweets}) => {
tweets.forEach(tweet => {
ReactDOM.render(<Tweet />, document.getElementById("app"));
});
})
.catch(console.error);
}
handleChange(event) {
let form = this.state.form;
form.username = event.target.value;
this.setState({
form: form
});
}
render () {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<p className="leadform-component-container">
<input type="text" placeholder="Username" required onChange={this.handleChange} />
</p>
<p className="leadform-component-container">
<input type="submit" value="Press me" />
</p>
</form>
</div>
)
}
}
ReactDOM.render(<Capture />, document.getElementById("app"));
Answer the question
In order to leave comments, you need to log in
In the simplest version:
class Capture extends React.Component {
constructor(props) {
super(props);
this.state = {
form: {
username: '',
},
tweets: [],
}
this.onFormSubmit = this.onFormSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
onFormSubmit(e) {
e.preventDefault()
axios.post('/', {
username: this.state.form.username
})
.then(({data: tweets}) => {
this.setState({ tweets });
})
.catch(console.error);
}
handleChange(event) {
const { form } = this.state;
form.username = event.target.value;
this.setState({ form });
}
render () {
const { tweets } = this.state;
return (
<div>
<form onSubmit={this.onFormSubmit}>
<p className="leadform-component-container">
<input
type="text"
placeholder="Username"
required
onChange={this.handleChange}
/>
</p>
<p className="leadform-component-container">
<input type="submit" value="Press me" />
</p>
</form>
<div>
{tweets.map((tweet, i) => <Tweet key={i} tweet={tweet} />)}
</div>
</div>
)
}
}
ReactDOM.render(<Capture />, document.getElementById("app"));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question