Building a ticket system for a movie app to learn react.
I’ve been trying to wrap my head around the useState and react hooks to make my seating system return an occupied seat after getting clicked on if it is vacant. What am I missing to make this work?
const PurchaseTicket = () => {
const seat = () => {
return (
<div className=' cursor-pointer bg-gray-500 h-[24px] w-[30px] m-1 rounded-t-[10px]'></div>
)
}
const seatOccupied = () => {
return (
<div className=' bg-cyan-500 h-[24px] w-[30px] m-1 rounded-t-[10px]'></div>
)
}
const [seating, setSeating] = useState([seat()])
const vacancy = () => {
setSeating((seatOccupied()))
}
const sideRow = () => {
return (
<>
<div className="m-auto pt-10 flex flex-row">
<div onClick={vacancy}>{seating}</div>
</>
)
}
return (
<>
<div className='m-15 flex flex-row justify-evenly'>
<div>{sideRow()}</div>
<div>{middleRow()}</div>
<div>{sideRow()}</div>
</div>
</>
)
}
2
Answers
seat
andseatOccupied
are not hooks. They’re components.tl;dr:
For what you’re trying to achieve, probably the simplest solution would be to have a seat component which has a
sold
property (among others you might need), along these lines:And the parent function would map through all seats and pass the
sold
prop to each, based onrowKey
andseatKey
, along these lines:React hook (
useState
in this context), can store value of any type with special behaviour for functions as said in the docs.To make it works, we add additional
vacant
state (you can use whatever name you like).but keep in mind that both
seat
andseatOccupied
should be pure, should take no arguments, and should return a value of any type (JSX in this context).But I myself, prefers to extract the seat and seatOccupied as separate components
and render it with conditional rendering:
or:
and render it like this:
So, you can choose whatever you like.
You can see my example here