Is there a way to use event.target to target specific sub-components and alter their style?
export default function Component(props) {
function MouseOver(event) {
event.target.style.boxShadow =
event.target.className === "container" &&
"4px 6px 4px rgba(0, 0, 0, 0.5)";
event.target.className.style.color = "#000";
}
function MouseOut(event) {
event.target.style.boxShadow = "none";
event.target.className.style.color = "#fff";
}
return (
<div
style={{
...Styles.root,
background: `url(${props.image})`,
backgroundSize: "cover",
...props.style,
}}
onMouseOver={MouseOver}
onMouseOut={MouseOut}
className={"container"}
>
<span style={Styles.title} className={"title"}>
{props.title}
</span>
</div>
);
}
const Styles = {
root: {
display: "flex",
},
title: {
width: "100%",
display: "flex",
color: "#FFF",
boxShadow: "none",
},
};
I want the title to change color when the mouse is over the component. Can event.target be used to target specific sub-components and alter their style?
This is the error that I get
categoriesCard.js:10 Uncaught TypeError: Cannot set properties of undefined (setting 'color')
at MouseOut (component.js:10:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
at invokeGuardedCallback (react-dom.development.js:4274:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4288:1)
at executeDispatch (react-dom.development.js:9038:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9070:1)
at processDispatchQueue (react-dom.development.js:9083:1)
at dispatchEventsForPlugins (react-dom.development.js:9094:1)
at react-dom.development.js:9285:1
"event.target" in your code is "MouseEvent" so it's not possible to change styles
why don't you add class name by using useState ?
export default function Component(props) {
const [onMouseOver, setOnMouseOver] = useState(false);
function MouseOver(event) {
setOnMouseOver(true);
// event.target.style.boxShadow =
// event.target.className === 'container' &&
// '4px 6px 4px rgba(0, 0, 0, 0.5)';
// event.target.className.style.color = '#000'; # Write this code in YourOwnClassName class
}
function MouseOut(event) {
setOnMouseOver(false);
// event.target.style.boxShadow = 'none';
// event.target.className.style.color = '#fff'; # Write this code in YourOwnClassName class
}
return (
<div
style={{
...Styles.root,
background: `url(${props.image})`,
backgroundSize: 'cover',
...props.style,
}}
onMouseOver={MouseOver}
onMouseOut={MouseOut}
className={onMouseOver ? 'container YourOwnClassName' :'container'}
>
<span style={Styles.title} className={'title'}>
{props.title}
</span>
</div>
);
}
actually, the greatest way to style is using "hover" css selector