styled-components: Extend existing component with additional prop for styling - reactjs

I'm using styled-components to override styling from an existing component, in this case ToggleButton from material ui. However I want my new component to have one additional property (hasMargin) that controls the style:
import {ToggleButton} from "#material-ui/lab";
import styled, {css} from "styled-components";
const StyledToggleButton = styled(ToggleButton)<{ hasMargin?: boolean }>`
&& {
color: red;
${props => props.hasMargin &&
css`
margin: 10px;
`}
}
`;
My intention is that StyledToggleButton behaves exactly like ToggleButton but has red color and can be called with an additional property hasMargin to turn on the margin css. I want to call it like this:
<StyledToggleButton
value={""} // ToggleButton prop
size={"small"} // ToggleButton prop
hasMargin={true} // My prop from StyledToggleButton
>
click
</StyledToggleButton>
But if I do it like this, in the browser console I get:
Warning: React does not recognize the `hasMargin` prop on a DOM element.
This is because StyledToggleButton seems to also pass hasMargin further to ToggleButton and ToggleButton of course can't and shouldn't deal with that (passing it down to the DOM element where it makes no sense). What is the best way to rewrite my code, so hasMargin is only processed by StyledToggleButton?
I've made a codesandbox to illustrate the issue. Thank you!

This is exactly what transient props are for.
All you need to do is prefix the prop with a $ and styled-components won't pass the prop to the underlying DOM element.
// Note the $ prefix in the prop name 👇
const StyledToggleButton = styled(ToggleButton)<{ $hasMargin?: boolean }>`
&& {
color: red;
// Just use the prop as normal
${(props) =>
props.$hasMargin &&
css`
margin: 10px;
`}
}
`;
<StyledToggleButton
value={""}
size={"small"}
{/* Assign the prop as normal */}
$hasMargin={true}
>
click
</StyledToggleButton>;
Here's your updated Codesandbox link with that error gone.

What about wrapping the ToggleButton with span and applying styles from there?
const StyledToggleButton = styled.span<{ hasMargin?: boolean }>`
margin: ${props => props.hasMargin && '50px'};
button {
color: red !important;
}
`
interface MyButtonProps extends ToggleButtonProps {
hasMargin?: boolean;
}
function MyButton(props: MyButtonProps) {
const { hasMargin, ...toggleButtonProps } = props;
return (
<StyledToggleButton hasMargin={hasMargin} >
<ToggleButton {...toggleButtonProps}>
{props.children}
</ToggleButton>
</StyledToggleButton>
);
}
export default function App() {
return (
<div className="App">
<MyButton value={""}>click</MyButton>
<MyButton value={""} size={"small"} hasMargin={true}>
click
</MyButton>
</div>
);
}

Related

How to reference a styled component that is in a different dom

I like to add styling to a styled component that is in a different dom.
Like this Material-ui Menu component example, the dashboard button is highlighted gray, and the menu drop is highlighted light blue.
They are written in the same component file but they are in different dom.
I like to add styling to the Menu component from Button component.
Is that possible?
Demo sandbox: https://codesandbox.io/s/si8tr5?file=/demo.js
Menu material ui official doc: https://mui.com/material-ui/react-menu/#basic-menu
index.jsx
import * as React from 'react';
import MenuItem from '#mui/material/MenuItem';
import {DisplayMenu, DisplayButton} from './styles'
export default function BasicMenu() {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<DisplayButton
id="basic-button"
aria-controls={open ? 'basic-menu' : undefined}
aria-haspopup="true"
aria-expanded={open ? 'true' : undefined}
onClick={handleClick}
>
Dashboard
</DisplayButton>
<DisplayMenu
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
'aria-labelledby': 'basic-button',
}}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</DisplayMenu>
</div>
);
}
styles.js
import styled from 'styled-components';
import Button from '#mui/material/Button';
import Menu from '#mui/material/Menu';
export const DisplayMenu = styled(Menu)`
padding: 20px;
`;
DisplayMenu.displayName = 'DisplayMenu';
export const DisplayButton = styled(Button)`
margin: 10px;
${DisplayMenu}{
& .MuiPaper-root {
width: 300px;
}
}
`;
DisplayButton.displayName = 'DisplayButton';
I know just doing this below will work but this is just an example and the reality is more complicated.
I just made it simple to ask this question here.
export const DisplayMenu = styled(Menu)`
padding: 20px;
& .MuiPaper-root {
width: 300px;
}
`;
Your current code won't work because you are applying styles to descendent DisplayMenu components (DisplayButton is a sibling). I don't really think it makes sense to do this but you could select the sibling:
export const DisplayButton = styled(Button)`
margin: 10px;
& + ${DisplayMenu}{
& .MuiPaper-root {
width: 300px;
}
}
`;
I think styling DisplayMenu directly makes the most sense (your last approach).
However If this is a permutation of DisplayMenu when used with a button, I think you should consider making the wrapper div into a styled component since that allows you to apply contextual styles to the menu (change its style based on 'where' it was used):
const MenuButton = styled.div`
${DisplayMenu}{
& .MuiPaper-root {
width: 300px;
}
`
// And use this in your component
<MenuButton>
<DisplayButton {...} />
<DisplayMenu {...} />
</MenuButton>
This way we only add the width to DisplayMenu when used within the context of MenuButton

Styled Components Props React js

I pass a property to my styled component. Basically I pass his height that starts with 400px.
And when I click a button it will go to 30px, but the way I did my div starts with 400px and when I click the button it goes to 30px and then doesn't expand the height size anymore:
export default function Menu() {
const [open, setOpen] = useState(true); // declare new state variable "open" with setter
const handleClick = e => {
e.preventDefault();
setOpen(false);
};
return (
<DivMenuButton height={open ? '400px' : '30px'}>
<button
style={{ margin:0, padding: 0, height: "30px", width: "100%", borderRadius:'0px' }}
onClick={handleClick}
>
Button
</button>
</DivMenuButton>
);
}
My styled component:
import React from 'react';
import styled from 'styled-components';
export const DivMenuButton = styled.div`
border: 0px;
background-color: #000; // was wrong syntax
width: 200px;
height: ${props => props.height}
`;
code:
https://codesandbox.io/s/beautiful-nightingale-fsm58
Your code is actually correct (almost).
The props and styled components parts are correct.
The thing you did wrong is that you always set open to false when clicking the button, instead of setting it to the opposite of what it was before.
So, instead of doing this:
const handleClick = e => {
e.preventDefault();
setOpen(false);
};
you should do this:
const handleClick = e => {
e.preventDefault();
setOpen(!open);
};

How can i change property overflow?

I have this code
import React from 'react';
import { AutoSizer, List } from 'react-virtualized';
const ListItem= () => (
<AutoSizer disableHeight>
{({ width }) => (
<List
height={700}
overscanRowCount={10}
width={width}
rowHeight={100}
rowCount={publicBids.length}
rowRenderer={this.rowRenderer}
style={{ overflow: 'hidden' }}
/>
)}
</AutoSizer>
)
In the react-virtualize docs say that List components have Grid component and inside have this class ReactVirtualized__Grid and ReactVirtualized__Grid__innerScrollContainer
How can i change the property overflow for these class ?
You can just import a css file to declare your class to override style, like this:
.ReactVirtualized__Grid__innerScrollContainer {
overflow: visible !important;
}
or If your using the styled-components, like this:
export const Container = styled.div`
.ReactVirtualized__Grid__innerScrollContainer {
overflow: visible !important;
}
`;
remember the element should be in Container which you want to override.

Material UI - font size in button label

I'm trying to figure out how to increase the font size of a label in my Material UI button in react.
I have a button setup:
import React from 'react';
import MyButton from '../materialui/Button.js';
const style = {
background: '#FF5349',
color: 'white',
padding: '0 30px',
textTransform: "uppercase",
};
const Start = () => (
<span>
<MyButton style={style} size="large">GET STARTED</MyButton>
</span>
);
export default Start;
I can't find a way to add font-size to the styles property.
Other stack overflow posts suggest doing it as an inline style using the style property, but that overrides my const definition.
If you don't want to add fontSize: '42px' to your styles object (probably because you want to reuse this somewhere else?) you can just build a new one with the style added for your button:
const Start = () => (
<span>
<MyButton style={{...style, fontSize: '42px'}} size="large">GET STARTED</MyButton>
</span>
);
I don't know if myButton in Material is the same of RaisedButton Anyway,
Button in Material-ui it's coming like Div > Button > Div > Div > span
So if you want to styling the button first of all you need to create a CSS class like
in your css file
This for styling button
.StylingButtonExample button{
background-color: red;
}
This for styling the text inside the button
.StylingButtonExample button div div span{
color: blue;
}
in react file
import RaisedButton from 'material-ui/RaisedButton';
<RaisedButton label="Default" className='StylingButtonExample' />
Hope this will help you and the others
Assuming the <MyButton /> Component is, in fact, the <RaisedButton /> Component that material-ui offers, you can simply apply your label styling to the labelStyle property.
Therefore, if you wanted to change the font-size to 42px, you could simply write it as follows:
<MyButton labelStyle={{ fontSize: '42px' }}>GET STARTED</MyButton>

Inline CSS styles in React: how to implement a:hover?

I quite like the inline CSS pattern in React and decided to use it.
However, you can't use the :hover and similar selectors. So what's the best way to implement highlight-on-hover while using inline CSS styles?
One suggestion from #reactjs is to have a Clickable component and use it like this:
<Clickable>
<Link />
</Clickable>
The Clickable has a hovered state and passes it as props to the Link. However, the Clickable (the way I implemented it) wraps the Link in a div so that it can set onMouseEnter and onMouseLeave to it. This makes things a bit complicated though (e.g. span wrapped in a div behaves differently than span).
Is there a simpler way?
I think onMouseEnter and onMouseLeave are the ways to go, but I don't see the need for an additional wrapper component. Here is how I implemented it:
var Link = React.createClass({
getInitialState: function(){
return {hover: false}
},
toggleHover: function(){
this.setState({hover: !this.state.hover})
},
render: function() {
var linkStyle;
if (this.state.hover) {
linkStyle = {backgroundColor: 'red'}
} else {
linkStyle = {backgroundColor: 'blue'}
}
return(
<div>
<a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
</div>
)
}
You can then use the state of hover (true/false) to change the style of the link.
Late to party but come with solution. You can use "&" to defines styles for hover nth Child etc:
day: {
display: "flex",
flex: "1",
justifyContent: "center",
alignItems: "center",
width: "50px",
height: "50px",
transition: "all 0.2s",
borderLeft: "solid 1px #cccccc",
"&:hover": {
background: "#efefef"
},
"&:last-child": {
borderRight: "solid 1px #cccccc"
}
},
I'm in the same situation. Really like the pattern of keeping the styling in the components but the hover states seems like the last hurdle.
What I did was writing a mixin that you can add to your component that needs hover states.
This mixin will add a new hovered property to the state of your component. It will be set to true if the user hovers over the main DOM node of the component and sets it back to false if the users leaves the element.
Now in your component render function you can do something like:
<button style={m(
this.styles.container,
this.state.hovered && this.styles.hover,
)}>{this.props.children}</button>
Now each time the state of the hovered state changes the component will rerender.
I've also create a sandbox repo for this that I use to test some of these patterns myself. Check it out if you want to see an example of my implementation.
https://github.com/Sitebase/cssinjs/tree/feature-interaction-mixin
You can use Radium - it is an open source tool for inline styles with ReactJS. It adds exactly the selectors you need. Very popular, check it out - Radium on npm
Here's my solution using React Hooks. It combines the spread operator and the ternary operator.
style.js
export default {
normal:{
background: 'purple',
color: '#ffffff'
},
hover: {
background: 'red'
}
}
Button.js
import React, {useState} from 'react';
import style from './style.js'
function Button(){
const [hover, setHover] = useState(false);
return(
<button
onMouseEnter={()=>{
setHover(true);
}}
onMouseLeave={()=>{
setHover(false);
}}
style={{
...style.normal,
...(hover ? style.hover : null)
}}>
MyButtonText
</button>
)
}
Full CSS support is exactly the reason this huge amount of CSSinJS libraries, to do this efficiently, you need to generate actual CSS, not inline styles. Also inline styles are much slower in react in a bigger system. Disclaimer - I maintain JSS.
Made Style It -- in part -- because of this reason (others being disagreements with implementation of other libs / syntax and inline stylings lack of support for prefixing property values). Believe we should be able to simply write CSS in JavaScript and have fully self contained components HTML-CSS-JS. With ES5 / ES6 template strings we now can and it can be pretty too! :)
npm install style-it --save
Functional Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return Style.it(`
.intro:hover {
color: red;
}
`,
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
);
}
}
export default Intro;
JSX Syntax (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
.intro:hover {
color: red;
}
`}
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
</Style>
);
}
}
export default Intro;
I found a clean way to do this with a wrapper around useState, which I call useHover.
No additional libraries/frameworks needed.
const App = () => {
const hover = useHover({backgroundColor: "LightBlue"})
return <p {...hover}>Hover me!</p>
}
Code for the wrapper:
function useHover(styleOnHover: CSSProperties, styleOnNotHover: CSSProperties = {})
{
const [style, setStyle] = React.useState(styleOnNotHover);
const onMouseEnter = () => setStyle(styleOnHover)
const onMouseLeave = () => setStyle(styleOnNotHover)
return {style, onMouseEnter, onMouseLeave}
}
Note that useHover has an optional second parameter for a style when the component is not hovered.
Try it out here
Heres is another option using CSS variables . This requires a css hover definition ahead of time so I guess its not pure inline, but is very little code and flexible.
css (setup a hover state) :
.p:hover:{
color:var(--hover-color) !important,
opacity:var(--hover-opacity)
}
react:
<p style={{'color':'red','--hover-color':'blue','--hover-opacity':0.5}}>
Adding on to Jonathan's answer, here are the events to cover the focus and active states, and a using onMouseOver instead of onMouseEnter since the latter will not bubble if you have any child elements within the target the event is being applied to.
var Link = React.createClass({
getInitialState: function(){
return {hover: false, active: false, focus: false}
},
toggleHover: function(){
this.setState({hover: !this.state.hover})
},
toggleActive: function(){
this.setState({active: !this.state.active})
},
toggleFocus: function(){
this.setState({focus: !this.state.focus})
},
render: function() {
var linkStyle;
if (this.state.hover) {
linkStyle = {backgroundColor: 'red'}
} else if (this.state.active) {
linkStyle = {backgroundColor: 'blue'}
} else if (this.state.focus) {
linkStyle = {backgroundColor: 'purple'}
}
return(
<div>
<a style={linkStyle}
onMouseOver={this.toggleHover}
onMouseOut={this.toggleHover}
onMouseUp={this.toggleActive}
onMouseDown={this.toggleActive}
onFocus={this.toggleFocus}>
Link
</a>
</div>
)
}
onMouseEnter={(e) => {
e.target.style.backgroundColor = '#e13570';
e.target.style.border = '2px solid rgb(31, 0, 69)';
e.target.style.boxShadow = '-2px 0px 7px 2px #e13570';
}}
onMouseLeave={(e) => {
e.target.style.backgroundColor = 'rgb(31, 0, 69)';
e.target.style.border = '2px solid #593676';
e.target.style.boxShadow = '-2px 0px 7px 2px #e13570';
}}
Set default properties in the style or class then call onMouseLeave() and onMouseEnter() to create a hover functionality.
Checkout Typestyle if you are using React with Typescript.
Below is a sample code for :hover
import {style} from "typestyle";
/** convert a style object to a CSS class name */
const niceColors = style({
transition: 'color .2s',
color: 'blue',
$nest: {
'&:hover': {
color: 'red'
}
}
});
<h1 className={niceColors}>Hello world</h1>
In regards to styled-components and react-router v4 you can do this:
import {NavLink} from 'react-router-dom'
const Link = styled(NavLink)`
background: blue;
&:hover {
color: white;
}
`
...
<Clickable><Link to="/somewhere">somewhere</Link></Clickable>
This can be a nice hack for having inline style inside a react component (and also using :hover CSS function):
...
<style>
{`.galleryThumbnail.selected:hover{outline:2px solid #00c6af}`}
</style>
...
The simple way is using ternary operator
var Link = React.createClass({
getInitialState: function(){
return {hover: false}
},
toggleHover: function(){
this.setState({hover: !this.state.hover})
},
render: function() {
var linkStyle;
if (this.state.hover) {
linkStyle = {backgroundColor: 'red'}
} else {
linkStyle = {backgroundColor: 'blue'}
}
return(
<div>
<a style={this.state.hover ? {"backgroundColor": 'red'}: {"backgroundColor": 'blue'}} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
</div>
)
}
You can use css modules as an alternative, and additionally react-css-modules for class name mapping.
That way you can import your styles as follows and use normal css scoped locally to your components:
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './table.css';
class Table extends React.Component {
render () {
return <div styleName='table'>
<div styleName='row'>
<div styleName='cell'>A0</div>
<div styleName='cell'>B0</div>
</div>
</div>;
}
}
export default CSSModules(Table, styles);
Here is a webpack css modules example
onMouseOver and onMouseLeave with setState at first seemed like a bit of overhead to me - but as this is how react works, it seems the easiest and cleanest solution to me.
rendering a theming css serverside for example, is also a good solution and keeps the react components more clean.
if you dont have to append dynamic styles to elements ( for example for a theming ) you should not use inline styles at all but use css classes instead.
this is a traditional html/css rule to keep html / JSX clean and simple.
This can be easily achived with material-ui makeStyles invocation:
import { makeStyles } from '#material-ui/core/styles';
makeStyles({
root: {
/* … */
'&:hover': { /* … */ }
},
});
This is a universal wrapper for hover written in typescript. The component will apply style passed via props 'hoverStyle' on hover event.
import React, { useState } from 'react';
export const Hover: React.FC<{
style?: React.CSSProperties;
hoverStyle: React.CSSProperties;
}> = ({ style = {}, hoverStyle, children }) => {
const [isHovered, setHovered] = useState(false);
const calculatedStyle = { ...style, ...(isHovered ? hoverStyle : {}) };
return (
<div
style={calculatedStyle}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
{children}
</div>
);
};
I did something similar to this, but I do not use material-ui or makeStyles. I added the hover as a condition in my css in a style object:
const styles = {
hoverStyle: {
color: 'grey',
'&:hover': { color: 'blue !important' },
}
};
var NavBar = (props) => {
const menuOptions = ['home', 'blog', 'projects', 'about'];
return (
<div>
<div>
{menuOptions.map((page) => <div style={styles.hoverStyle} key={page}>{page}</div> )}
</div>
</div>
);
};
This worked for me.
You can just create an abstract hovering class e.g. for the color.
.hoverClassColor:hover {
color:var(--hover-color) !important;
}
Then for all Elements you wanna changes the color to red on hovering:
render() {
return <a className={'hoverClassColor'} style={{'--hover-color':'red'}}>Test</a>
}
For me its like inline, cause the classes are abstract and can be reused for all of your elements you wanna implement a color hovering.
I use this trick, a mix between inline-style and css:
//inline-style:
const button = {
fontSize: "2em",
};
return (
<div style={button} data-hover="button">
<style>{`[data-hover="button"]:hover {
font-size: 2.1em !important;
}`}</style>
{this.props.text}
</div>
);
Easiest way 2022:
useRef + inline onMouseOver/onMouseOut
example:
var bottomAtag = useRef(null)
...then inside return (
<a ref={bottomAtag} onMouseOver={() => bottomAtag.current.style.color='#0F0'} ...></a>
With a using of the hooks:
const useFade = () => {
const [ fade, setFade ] = useState(false);
const onMouseEnter = () => {
setFade(true);
};
const onMouseLeave = () => {
setFade(false);
};
const fadeStyle = !fade ? {
opacity: 1, transition: 'all .2s ease-in-out',
} : {
opacity: .5, transition: 'all .2s ease-in-out',
};
return { fadeStyle, onMouseEnter, onMouseLeave };
};
const ListItem = ({ style }) => {
const { fadeStyle, ...fadeProps } = useFade();
return (
<Paper
style={{...fadeStyle, ...style}}
{...fadeProps}
>
{...}
</Paper>
);
};
<Hoverable hoverStyle={styles.linkHover}>
<a href="https://example.com" style={styles.link}>
Go
</a>
</Hoverable>
Where Hoverable is defined as:
function Hoverable(props) {
const [hover, setHover] = useState(false);
const child = Children.only(props.children);
const onHoverChange = useCallback(
e => {
const name = e.type === "mouseenter" ? "onMouseEnter" : "onMouseLeave";
setHover(!hover);
if (child.props[name]) {
child.props[name](e);
}
},
[setHover, hover, child]
);
return React.cloneElement(child, {
onMouseEnter: onHoverChange,
onMouseLeave: onHoverChange,
style: Object.assign({}, child.props.style, hover ? props.hoverStyle : {})
});
}
I use a pretty hack-ish solution for this in one of my recent applications that works for my purposes, and I find it quicker than writing custom hover settings functions in vanilla js (though, I recognize, maybe not a best practice in most environments..) So, in case you're still interested, here goes.
I create a parent element just for the sake of holding the inline javascript styles, then a child with a className or id that my css stylesheet will latch onto and write the hover style in my dedicated css file. This works because the more granular child element receives the inline js styles via inheritance, but has its hover styles overridden by the css file.
So basically, my actual css file exists for the sole purpose of holding hover effects, nothing else. This makes it pretty concise and easy to manage, and allows me to do the heavy-lifting in my in-line React component styles.
Here's an example:
const styles = {
container: {
height: '3em',
backgroundColor: 'white',
display: 'flex',
flexDirection: 'row',
alignItems: 'stretch',
justifyContent: 'flex-start',
borderBottom: '1px solid gainsboro',
},
parent: {
display: 'flex',
flex: 1,
flexDirection: 'row',
alignItems: 'stretch',
justifyContent: 'flex-start',
color: 'darkgrey',
},
child: {
width: '6em',
textAlign: 'center',
verticalAlign: 'middle',
lineHeight: '3em',
},
};
var NavBar = (props) => {
const menuOptions = ['home', 'blog', 'projects', 'about'];
return (
<div style={styles.container}>
<div style={styles.parent}>
{menuOptions.map((page) => <div className={'navBarOption'} style={styles.child} key={page}>{page}</div> )}
</div>
</div>
);
};
ReactDOM.render(
<NavBar/>,
document.getElementById('app')
);
.navBarOption:hover {
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Notice that the "child" inline style does not have a "color" property set. If it did, this would not work because the inline style would take precedence over my stylesheet.
I'm not 100% sure if this is the answer, but its the trick i use to simulate the CSS :hover effect with colours and images inline.
`This works best with an image`
class TestHover extends React.PureComponent {
render() {
const landingImage = {
"backgroundImage": "url(https://i.dailymail.co.uk/i/pix/2015/09/01/18/2BE1E88B00000578-3218613-image-m-5_1441127035222.jpg)",
"BackgroundColor": "Red", `this can be any color`
"minHeight": "100%",
"backgroundAttachment": "fixed",
"backgroundPosition": "center",
"backgroundRepeat": "no-repeat",
"backgroundSize": "cover",
"opacity": "0.8", `the hove trick is here in the opcaity slightly see through gives the effect when the background color changes`
}
return (
<aside className="menu">
<div className="menu-item">
<div style={landingImage}>SOME TEXT</div>
</div>
</aside>
);
}
}
ReactDOM.render(
<TestHover />,
document.getElementById("root")
);
CSS:
.menu {
top: 2.70em;
bottom: 0px;
width: 100%;
position: absolute;
}
.menu-item {
cursor: pointer;
height: 100%;
font-size: 2em;
line-height: 1.3em;
color: #000;
font-family: "Poppins";
font-style: italic;
font-weight: 800;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
}
Before hover
.menu-item:nth-child(1) {
color: white;
background-color: #001b37;
}
On hover
.menu-item:nth-child(1):hover {
color: green;
background-color: white;
}
Example: https://codepen.io/roryfn/pen/dxyYqj?editors=0011
Here is how I do it with hooks in functional components. With onMouseEnter/Leave, im setting the color as state directly and consume it in the style prop of element (instead of setting hover state and using ternaries to change the state as shown in previous answers).
function App() {
const [col, setCol] = React.useState('white');
return (
<div className="App">
<button
style={{background: `${col}`}}
onMouseEnter={() => setCol("red")}
onMouseLeave={() => setCol("white")}
>
Red
</button>
</div>
);
}
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js" integrity="sha256-3vo65ZXn5pfsCfGM5H55X+SmwJHBlyNHPwRmWAPgJnM=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js" integrity="sha256-qVsF1ftL3vUq8RFOLwPnKimXOLo72xguDliIxeffHRc=" crossorigin="anonymous"></script>
<div id='root'></div>
This solution does use stylesheets. However, If your application uses an index.css - i.e. has a stylesheet that gets imported into your top-level component, you could just write the following code in there
.hoverEffect:hover {
//add some hover styles
}
Then in your React component, just add the className "hoverEffect" to apply the hover effect "inline".
If the hover state is being passed down as a prop, and you only want it to be applied to the child component, remove the :hover in your index.css, and do this instead.
function Link(props) {
return (
<a className={props.isHovered ? "hoverEffect" : ""}>Hover me<a/>
)
}
Directly use tag in your component like this:
<Wrapper>
<style>
.custom-class{
// CSS here
}
.custom-class:hover{
//query selector
}
</style>
<div className="custom-class"></div>
</Wrapper>

Resources