I am using react tailwindcss v3, but I am unable to figure out how could I change the SVG stroke color on hover of its parent element.
This is the code where I have rendered the SVG component
import Arrow from "../../assets/logos/Arrow_up_right";
const MyComponent= () => {
const onhover = "blue";
const normal = "red";
return (
<ul className='list-none px-2'>
<li> className='my-2 h-12 w-12 flex items-center justify-center rounded-lg bg-gray-100 hover:cursor-pointer'>
<Arrow stroke={normal} />
</li>
</ul>
};
Arrow is the component which returns SVG. I have passed a prop to it which then is used in providing color to stroke of arrow svg.
here is the SVG component:
const Arrow_up_right = ({ stroke }) => {
return (
<svg
width='8'
height='8'
viewBox='0 0 8 8'
fill='none'
xmlns='http://www.w3.org/2000/svg'
>
<path
d='M0.666626 7.33335L7.33329 0.666687M7.33329 0.666687H0.666626M7.33329 0.666687V7.33335'
stroke={stroke}
stroke-linecap='round'
stroke-linejoin='round'
/>
</svg>
);
};
export default Arrow_up_right;
The Problem now is I want the value of prop being passed should change on hover of li,
if that can't be done then please suggest some other way to do it.
Any help would be appreciated. :)
CodePudding user response:
You could use onMouseEnter and onMouseLeave together with useState to set hover state and based on that pass correct color to Arrow.
But in my opinion better way would be to utilize tailwind group class. You can set group class on li and then in the Arrow_up_right component use tailwind stroke classes stroke-red-500 group-hover:stroke-blue-500 (change number to match your desired color) on svg tag and remove stroke from path.
CodePudding user response:
Try this approach with CSS Variables and Tailwind Utilities, where we pass initial values from the parent component to the child and then use an extra class in the parent <li>.
index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer utilities {
.arrow svg path {
stroke: var(--normal);
}
,
.arrow:hover svg path {
stroke: var(--hover);
}
}
Arrow.jsx
export const Arrow = ({ strokeColor, strokeHover }) => {
return (
<svg width="8" height="8" viewBox="0 0 8 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M0.666626 7.33335L7.33329 0.666687M7.33329 0.666687H0.666626M7.33329 0.666687V7.33335"
style={{ '--normal': strokeColor, '--hover': strokeHover }}
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
};
App.jsx
function App() {
const onhover = 'blue';
const normal = 'red';
return (
<div className="p-6">
<ul className="list-none px-2">
<li className="my-2 h-12 w-12 flex items-center justify-center rounded-lg bg-gray-100 hover:cursor-pointer arrow hover:arrow">
<Arrow strokeColor={normal} strokeHover={onhover} />
</li>
</ul>
</div>
);
}

