Reputation: 39
I'm making a sidebar with React and Tailwind. This is the content of Sidebar.jsx
.
import { FC } from "react";
import React, { useState } from 'react'
import { Link, NavLink } from "react-router-dom";
import HomeIcon from '@mui/icons-material/Home';
import ConstructionIcon from '@mui/icons-material/Construction';
import ContentPasteIcon from '@mui/icons-material/ContentPaste';
import SettingsIcon from '@mui/icons-material/Settings';
import SummarizeIcon from '@mui/icons-material/Summarize';
import {FaBars} from "react-icons/fa"
const SideBar: FC = () => {
const [open, setOpen] = useState(true);
const toggle = () => {
setOpen(!open);
};
return (
<div className="flex">
<div className={'bg-black w-[300px] h-100vh ${open: "w-[300px]" ? "w-[50px]"} transition-all duration-500'}>
<div className={'flex align-center px-[15px] py-[20px]'}>
<h1 className={'${open? "block" : "hidden"} text-white text-[30px]'}>
Logo
</h1>
<div className={'${open: "ml-[50px]": "ml-[0px]"} flex text-white text-[25px] mt-[12px] ml-[50px]'}>
<FaBars onClick={toggle}/>
</div>
</div>
<NavLink
className={'flex text-white px-[15px] py-[20px] gap-[15px] transition-all duration-500'}
to="/"
>
<HomeIcon className={'text-[20px]'}/>
<div className={'${open? "block": "hidden"} text-[20px]'}>
DASHBOARD
</div>
</NavLink>
</div>
</div>
);
};
export default SideBar;
Problem: On clicking the <FaBars />
icon, I need the sidebar to toggle between expanding and contracting, and I need the text of the NavLink to disappear, but it's not showing any change in width on click. Why is the "hidden" class not working, and why is the width of the sidebar not changed?
My attempts: I've inspected the output, and made sure the toggle function is being called. I just don't know why the width isn't changing from w-[300px]
to w-[50px]
Upvotes: 1
Views: 2385
Reputation: 174
The way I used conditional tailwind for my svelte project is as bellow. Here I rendered the chat messages based on it's background
<div class="flex {message.background ? 'justify-start' : 'justify-end'} mx-3">
<div class="bg-[{message.background ? '#f6f6f6' : '#001e3c'}]
{message.background ? 'text-black' : 'text-white'}
my-2
p-3
rounded-md
w-[300px]">
{message.messageText}
</div>
if you are willing to add tailwind css based on some conditions then you can write it like
<div className= "{open ? 'block' : 'hidden'} text-[20px]">
Upvotes: 0
Reputation: 476
I think you are using the template string syntax incorrectly.
className={`${open? "block": "hidden"} text-[20px]`}
Upvotes: 2
Reputation: 46
If you need to write jsx expressions within classNames, try using backticks( `` ) , not single quote ('') or double quotes(" ")
also, you are doing ternary operators in the wrong way. you can read more about ternary operators here
ex:
<div className={`bg-black w-[300px] h-100vh ${open? "w-[300px]" : "w-[50px]"} transition-all duration-500`}>
//your code here
</div>
Upvotes: 0