I am creating my first app in React. It is a cinema booking app. I have component which is a single seat in screening room and a screening room component build with list of seats and reservation. I need access to seat id which user will choose and send this data to api after clicking on submit button. The way I am doing this now doesn't work. I think that because I do not render single seat in screeningRoom component but list.
Here is my code:
Seat component
import React, { Component } from "react";
import "./seat.css";
class Seat extends Component {
constructor(props) {
super(props);
this.state = {
bgc: this.props.ticket ? "red" : "grey",
seatId: ""
};
//console.log(this.props)
}
reserve = () => {
if (!this.props.ticket) {
this.state.bgc === "grey"
? this.setState({ bgc: "green" })
: this.setState({ bgc: "grey" });
}
this.setState({ seatId: this.props.id });
//console.log (this.props.id)
};
render() {
return (
<div>
<input
className="seat"
style={{ backgroundColor: this.state.bgc }}
onClick={this.reserve}
></input>
</div>
);
}
}
export default Seat;
screeningRoom component
import React, { Component } from "react";
import axios from "axios";
import Seat from "./seats";
import "./screeningRoom.css";
export default class screeningRoom extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
seats: [],
room: [],
clicked: []
};
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
async componentDidMount() {
this.setState({ loading: true });
const {
match: { params }
} = this.props;
const res = await axios.get(
`http://localhost:8080/api/shows/${params.id}/seats`
);
//console.log(res)
this.setState({ seats: res.data.seats });
//console.log(this.state.seats)
this.setState({ room: res.data.name });
}
renderSeats() {
return this.state.seats.map(seat => (
<Seat
onClick={this.handleClick.bind(this)}
key={seat._id}
value={seat._id}
ticket={seat.ticket}
seat={seat}
/>
));
}
handleSubmit(e) {
e.preventDefault();
console.log(e.target.value);
}
handleClick(e) {
console.log(e.currentTarget.value);
}
render() {
return (
<div
className="screening-room d-flex flex-column justify-contnt-center align-items-center"
style={{ marginTop: 20 }}
>
<h3 style={{ color: "white" }}>Room: {this.state.room} </h3>
<div className="screen">screen</div>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className={this.state.room}>{this.renderSeats()}</div>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
targetis an inefficient way to handle data, you already know the value, just use it directly.onClick={() => this.handleClick(value)}