Home > Software design >  Multiple condition in ternary operator in jsx my component not showing
Multiple condition in ternary operator in jsx my component not showing

Time:02-25

I am using ternary operator in jsx to show any of my component. The issue is that when I press one of my button and set my state showChat to 'true' it doesn't show my component "Chat". My ternary condition seems fine so I don't understand why this issue occur. Any idea how can I fix this ?

Thank you :)


const Chatroom = () => {
    
    ... other states ...
    const [showChat, setShowChat] = useState(false);
    const [showRoomList, setShowRoomList] = useState(false);

    const createRoom = () => {
        if (username !== "" && room !== "") {
            socket.emit("join_room", room);
            setShowChat(true);
        }
    }

    const listeRoom = () => {
        if (username !== "") {
            socket.emit("room_list", 'roomList');
            setShowRoomList(true);
        }
    }

    ...

    return (
        <>
        <CssBaseline/>
        <main>
            <div className={classes.container}>
            <Container maxWidth="md">
                {!showChat || !showRoomList ? (
                    <Button onClick={createRoom} disabled={disable} color='primary' variant="contained"> Créer une room </Button>
                    <Button onClick={listeRoom} disabled={enable} color='primary' variant="outlined"> Liste des rooms </Button>
                )
                : showRoomList ? (
                    <ListeRooms socket={socket} username={username}/>
                ) 
                :(
                    <Chat socket={socket} username={username} room={room}/>
                )}
            </Container>
        </div>
    </main>
    </>
    )
}

export default Chatroom;

CodePudding user response:

I don't recommend this way of conditional rendering because as you can see it is tricky. Probably you made a mistake here

 {!showChat || !showRoomList ? ( ->  {!showChat && !showRoomList

I recommend you to do this in that way

<Container maxWidth="md">
  {!showChat && !showRoomList && (<Button onClick={createRoom}..../>....)}
  {showRoomList && <ListeRooms socket=..../>}
  {showChat && <Chat.../>}
</Container>
  • Related