React Customize Google calendar's tooltip does't appear - reactjs

I am using this api to create customize google calendar.
https://github.com/ericz1803/react-google-calendar
Here are the codeSandbox for demo, the tooltip is perfectly working.
https://codesandbox.io/s/cocky-rgb-2y3t7?file=/src/App.js
Then, I copied the same code into mine project with all path, API ... changed.
Every things works well, but the tooltip doesn't appear any more.
import React from "react";
import "./styles.css";
import Calendar from "#ericz1803/react-google-calendar";
import { css } from "#emotion/react";
const API_KEY = "AIzaSyAKzScoADeBmp6qUsEzrwZhLqb6WARNFOo";
//replace calendar id with one you want to test
let calendars = [
{ calendarId: "c_7q0ai3mn1p9b880f7llhbnv364#group.calendar.google.com" }
];
let styles = {
//you can use object styles
calendar: {
borderWidth: "3px" //make outer edge of calendar thicker
},
today: css`
/* highlight today by making the text red and giving it a red border */
color: red;
border: 1px solid red;
`
};
export default function App() {
return (
<div className="App">
<body>
<div
style={{
width: "90%",
paddingTop: "50px",
paddingBottom: "50px",
margin: "auto",
maxWidth: "1200px"
}}
>
<Calendar apiKey={API_KEY} calendars={calendars} styles={styles} />
</div>
</body>
</div>
);
}

There is open issue for same on github.
Till it gets fixed, use the same version of the package which is used in the sandbox demo, it doesn't have that bug.
"#ericz1803/react-google-calendar": "4.0.1"

Related

React Create a Horizontal Divider with Text In between

I need to create a React component that is a Horizontal Divider with a content like text In between. All the resources I have online is unable to help me get this done. I tried a material-ui divider by creating a Divider component and placing my text in-between like the example below:
<Divider>Or</Divider>
But I get the error:
hr is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.
I need to achieve this in the image below:
Any help will be appreciated.
These are my codes below:
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import List from '#material-ui/core/List';
import Divider from '#material-ui/core/Divider';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
}));
export default function ListDividers() {
const classes = useStyles();
return (
<List component="nav" className={classes.root} aria-label="mailbox
folders">
<Divider>Or</Divider>
</List>
);
}
Using Material UI.
import React from "react";
import { makeStyles } from "#material-ui/core";
const useStyles = makeStyles(theme => ({
container: {
display: "flex",
alignItems: "center"
},
border: {
borderBottom: "2px solid lightgray",
width: "100%"
},
content: {
paddingTop: theme.spacing(0.5),
paddingBottom: theme.spacing(0.5),
paddingRight: theme.spacing(2),
paddingLeft: theme.spacing(2),
fontWeight: 500,
fontSize: 22,
color: "lightgray"
}
}));
const DividerWithText = ({ children }) => {
const classes = useStyles();
return (
<div className={classes.container}>
<div className={classes.border} />
<span className={classes.content}>{children}</span>
<div className={classes.border} />
</div>
);
};
export default DividerWithText;
You can import and use it like the below
<DividerWithText>Or</DividerWithText>
Result
Here a custom example of what you could do : repro on stackblitz
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
const App = () => {
return <Divider>Or</Divider>;
};
const Divider = ({ children }) => {
return (
<div className="container">
<div className="border" />
<span className="content">
{children}
</span>
<div className="border" />
</div>
);
};
render(<App />, document.getElementById("root"));
And the CSS:
.container{
display: flex;
align-items: center;
}
.border{
border-bottom: 1px solid black;
width: 100%;
}
.content {
padding: 0 10px 0 10px;
}
Update 29/03/2022
That's now possible with Material UI 🔥
https://mui.com/components/dividers/#dividers-with-text
You may want different spacing sometime
<Divider spacing={1}>Hello World</Divider>
Or
<Divider spacing={2}>Hello World</Divider>
For a configurable spacing here a Github Gist
Or a playground in codesandbox if you prefer
The current answer causes any text with spaces in-between to wrap:
If that happens, changing width: 100% to flexGrow: 1 should solve it:
border: {
borderBottom: "2px solid lightgray",
flexGrow: 1,
}
Unfortunately for now, having Divider with text on it in MUI is only available in v5, which is still in alpha stage. If you would like to try, you can download the alpha package, but be warned that it is still highly unstable and a lot of changes might be needed to migrate to v5, which is not very worth it.
GitHub discussion: https://github.com/mui-org/material-ui/issues/24036

External Css not working in Gatsby react project

I am not sure if this is the correct way of using CSS in gatsby but for some reason my external syles are not being applied in gatsby project.
This is what I am doing it
import { Link } from "gatsby"
import PropTypes from "prop-types"
import React from "react"
import "./header.css"
const Header = (props) => {
return (
<header
style={{
background: `black`,
marginBottom: `1.45rem`,
}}
>
<div
style={{
margin: `0 auto`,
maxWidth: 960,
padding: `1.45rem 1.0875rem`,
}}
>
<h1 style={{ margin: 0 }}>
<Link
to="/"
style={{
color: `white`,
textDecoration: `none`,
}}
>
{props.siteTitle} <span className="header-description"> {props.description} </span>
</Link>
</h1>
</div>
</header>
)
}
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
and this is my header.css
.header-description {
font-size: 12;
}
Your css is invalid. font-size can't have unitless values except for 0.
Maybe you wanted it to be 12px?
what i usually do is create and import index.css into layer component (or any other wrapping component) aaaand then import individual/uniques/modules to that index.css. So the main index.css becomes sort of like a hub for css files which then is being imported only in once place. well, obviously if you would use css modules you would have to import them into your react components, but by the looks of it you are just using classnames. so...yea, try my method, maybe that helps? Theres also like 4 tutorials on how to import and use css and various styling methodologies in gatsby docs.

Screen Change Orientation Listener ReactJS

I am trying to make a different button position for both portrait and landscape versions of the React application I’m working on. I tried learning about event listeners and referred to these two posts, and inspected the console for a message while trying to rotate using an iPhoneX view on Google Chrome. However, I don’t seem to see a message of 'changed orientation'. Does anyone know the problem with my code? Feel free to ask for more clarification.
Welcome.js
import React, { Component} from "react";
import { Link } from "react-router-dom";
import "../style/App.css";
import { Typography, Button, Card, Grid } from "#material-ui/core";
import homepage2 from "../images/homepage2.png";
export default class WelcomeComponent extends Component {
onOrientationChange = (event) => {
console.log('changed orientation');
}
render() {
return (
<div onOrientationChange={this.onOrientationChange}
style={{
minHeight: "100vh",
backgroundImage: `url(${homepage2})`,
backgroundPosition: "center",
backgroundSize: "cover"
}}
>
<div
style={{
textAlign: "center",
verticalAlign: "bottom",
bottom: "0px"
}}
>
<Link to="/Language">
<Button
variant="contained"
color="secondary"
size="large"
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%,-50%)"
}}
>
CONTINUE
</Button>
</Link>
</div>
</div>
);
}
}

Material UI: bug with react transition group v 2.2.0

I'm using <Transition> as explained in main documentation of React Transition Group.
import React from 'react';
import PropTypes from 'prop-types';
import Transition from 'react-transition-group/Transition';
const defaultStyle = {
transition: `opacity 300ms ease-in-out`,
opacity: 0,
};
const transitionStyles = {
entering: { opacity: 1 },
entered: { opacity: 1 },
};
const Fade = ({
in: inProp,
children,
}) => (
<Transition in={inProp} timeout={300}>
{state => (
<div
style={{
...defaultStyle,
...transitionStyles[state],
}}
>
{children}
</div>
)}
</Transition>
);
Fade.propTypes = {
in: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
};
export default Fade;
It works, but not so well with Material UI, especially with Buttons, everywhere on my app: when I click on them, appears a white div behind them:
<div in="false" style="position: absolute; top: -88.218px; left: -97.218px; height: 220.436px; width: 220.436px; border-radius: 50%; background-color: rgb(255, 255, 255);"></div>
and this weird error in console:
Warning: Unknown props `onExited`, `appear`, `enter`, `exit` on <div> tag. Remove these props from the element.
Those props are about Transition, but I can't understand the problem.
I'm using React 15.6.1, Material ui 0.18.7 and React Transition Group 2.2.0
I encountered this bug today, and I logged an issue + repro case on their github.
https://github.com/callemall/material-ui/issues/8046
(repro: https://codesandbox.io/s/q9o5q0l5nw)
I have tested in v1.0.0-beta.8 and it looks like it's working fine (https://codesandbox.io/s/r5nplz89nn).
The project's stance is essentially "material-ui v0.x is legacy code".
So your options are either; disable ripples across your app, fix it for them via a PR, or move to the unfinished v1 beta branch.

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