Reputation: 87
I'm new to React forms and have been stuck on this for well over a week. I have a list of restaurants that I generated by mapping through nearby
places. On each list item I have a textarea Component. My goal is to submit a review on a restaurant from the list and then have that review appear on the corresponding
Component on my map. However, when I submit a review for one restaurant that review shows on all the restaurants' InfoWindows.
On my onSubmit function I set the userReview
value to query
and then on <InfoWindow/>
I return <div>{query}</div>
. I know I need
a way to 'grab-hold' of or match an id or something of the corresponding restaurant InfoWindow but I cannot figure out the way to do so.
// APP.JS SNIPPET WITH <INFOWINDOW/>
{nearbyRestaurants.map((place) => (
<Marker
onClick={() => {
setSelectedRestaurants(place);
}}
/>
))}
{selectedRestaurants ? (
<InfoWindow>
<div>
<h4>{selectedRestaurants.name}</h4>
{/* I NEED TO MATCH/FIX THIS */}
<div>{query}</div>
</div>
</InfoWindow>
) : null}
// LIST COMPONENT
export default function List2({
nearbyRestaurants,
setQuery,
}) {
return (
<div>
<ul>
{nearbyRestaurants.map((place) => (
<div>
<li>
{place.name}
<NewReview
key={place.name}
name={place.name}
setQuery={setQuery}
/>
</li>
</div>
))}
</ul>
</div>
);
}
// TEXTAREA/REVIEW COMPONENT
class NewReview extends Component {
constructor(props) {
super(props);
this.state = {
userReview: ""
};
this.handleChange = this.handleChange.bind(this);
this.sumbitForm = this.sumbitForm.bind(this);
}
handleChange(event) {
this.setState({
userReview: event.target.value,
[event.target.name]: event.target.value
});
}
sumbitForm(event) {
event.preventDefault();
this.setState({
userReview: ""
});
this.props.setQuery(this.state.userReview);
}
render() {
return (
<form onSubmit={this.sumbitForm}>
<textarea
value={this.state.userReview}
name={this.props.name}
placeholder="Add a Review..."
onChange={this.handleChange}
/>
<button className="submit-button" type="submit">
submit
</button>
</form>
);
}
}
export default NewReview;
Upvotes: 0
Views: 568
Reputation: 118
Not sure how your states are structured, but you may have to modify it a bit. On your submitForm you are already setting the state for the review, but not setting the state for which restaurant the review belongs to. You already pass the restaurant name to the NewReview component, so one thing you can do is restructure the setState to be something like this:
sumbitForm(event) {
event.preventDefault();
this.setState({
restaurantName: this.props.name,
userReview: this.state.userReview,
});
this.props.setQuery(this.props.name, this.state.userReview);
}
Make sure to update setQuery to update including name. I see that you already have a 'selectedRestaurants' object maybe you can add the review state to that:
selectedRestaurant: {
name: 'RestaurantName',
review: 'RestaurantReview',
}
Depends really on how you are handling the state.
Upvotes: 1