How can I use two transitions with material ui? - reactjs

What I'm trying to do is use Fade and Slide in the same component.
<Slide in={isValid} timeout={timeout} direction="left">
<Fade in={isValid} timeout={timeout}>
<Foo />
</Fade>
</Slide>
But it doesn't work.
When isValid is true, it slides the component without the fade effect and when it's false, the component just blinks and disappears.
How can I make it work? I don't want to use makeStyle.

The Slide and the Fade components both change the style.transition property, so if they act on the same element they clobber portions of the other's work.
The way to get this to work is for them to act on different elements. Introducing a div between the two transitions gets the desired behavior.
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import Switch from "#material-ui/core/Switch";
import Paper from "#material-ui/core/Paper";
import Fade from "#material-ui/core/Fade";
import Slide from "#material-ui/core/Slide";
import FormControlLabel from "#material-ui/core/FormControlLabel";
const useStyles = makeStyles(theme => ({
root: {
height: 180
},
container: {
display: "flex"
},
paper: {
margin: theme.spacing(1),
backgroundColor: "lightblue"
},
svg: {
width: 100,
height: 100
},
polygon: {
fill: theme.palette.primary.main,
stroke: theme.palette.divider,
strokeWidth: 1
}
}));
export default function SlideAndFade() {
const classes = useStyles();
const [checked, setChecked] = React.useState(false);
const handleChange = () => {
setChecked(prev => !prev);
};
return (
<div className={classes.root}>
<FormControlLabel
control={<Switch checked={checked} onChange={handleChange} />}
label="Show"
/>
<div className={classes.container}>
<Slide in={checked} timeout={1000}>
<div>
<Fade in={checked} timeout={1000}>
<Paper elevation={4} className={classes.paper}>
<svg className={classes.svg}>
<polygon
points="0,100 50,00, 100,100"
className={classes.polygon}
/>
</svg>
</Paper>
</Fade>
</div>
</Slide>
</div>
</div>
);
}

I realized that if you wrap the transition in a div or other element to make it as a container, it will work.
<Slide in={isValid} timeout={timeout} direction="left">
<div> // adding this div will make it work
<Fade in={isValid} timeout={timeout}>
<Foo />
</Fade>
</div>
</Slide>
And then you can just create your own Fade component that wraps a div.
const MyFade = React.forwardRef(
({ children, in: In, timeout, ...otherProps }, ref) => {
return (
<div ref={ref} {...otherProps}>
<Fade in={In} timeout={timeout}>
{children}
</Fade>
</div>
);
}
);
Thanks to #Ryan Cogswe that also helped in this.

Related

How to access values from context in a separate functional component

I'm trying to build a simple light mode/dark mode into my app I saw this example on Material UI for light/dark mode but I'm not sure how I can get access to the value for when the user clicks toggleColorMode in my Header component if it's being set in toggleColorMode function?
I guess my question is how can I get access to the value of light/dark mode of the context in my Header component if it's in a different function?
Here is my code.
import React, { useState, useEffect } from "react";
import MoreVertIcon from "#mui/icons-material/MoreVert";
import DarkModeIcon from "#mui/icons-material/DarkMode";
import LightModeIcon from "#mui/icons-material/LightMode";
import Paper from "#mui/material/Paper";
import { useTheme, ThemeProvider, createTheme } from "#mui/material/styles";
import IconButton from "#mui/material/IconButton";
import Navigation from "../Navigation/Navigation";
const ColorModeContext = React.createContext({ toggleColorMode: () => {} });
export const Header = (props) => {
const { mode } = props;
const theme = useTheme();
const colorMode = React.useContext(ColorModeContext);
console.log("mode is...", mode);
return (
<div className="header-container">
<Paper
elevation={3}
style={{ backgroundColor: "#1F1F1F", padding: "15px" }}
>
<div
className="header-contents"
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<div
className="logo"
style={{ display: "flex", alignItems: "center" }}
>
<img
src="/images/header-logo.png"
alt="URL Logo Shortener"
width={"50px"}
/>
<h1 style={{ color: "#ea80fc", paddingLeft: "20px" }}>
URL Shortener
</h1>
</div>
<div className="settings">
<IconButton
sx={{ ml: 1 }}
onClick={colorMode.toggleColorMode}
color="inherit"
aria-label="dark/light mode"
>
{theme.palette.mode === "dark" ? (
<DarkModeIcon
style={{
cursor: "pointer",
marginRight: "10px",
}}
/>
) : (
<LightModeIcon
style={{
cursor: "pointer",
marginRight: "10px",
}}
/>
)}
</IconButton>
<IconButton aria-label="settings">
<MoreVertIcon style={{ color: "#fff", cursor: "pointer" }} />
</IconButton>
</div>
</div>
</Paper>
{/* Navigation */}
<Navigation />
</div>
);
};
export default function ToggleColorMode() {
const [mode, setMode] = React.useState("light");
const colorMode = React.useMemo(
() => ({
toggleColorMode: () => {
setMode((prevMode) => (prevMode === "light" ? "dark" : "light"));
},
}),
[]
);
const theme = React.useMemo(
() =>
createTheme({
palette: {
mode,
},
}),
[mode]
);
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<Header mode={mode} />
</ThemeProvider>
</ColorModeContext.Provider>
);
}
Read the documentation: createContext, useContext. You need to render a ContextProvider in your parent (or top-level) component, then you can get the data in any component in the tree like const { theme } = useContext(ColorModeContext);.
You don't need to pass the mode as props, put it as one of the values in the context and access it.
Here's how you would render it in your example:
<ColorModeContext.Provider value={{colorMode, theme}}>
<Header />
</ColorModeContext.Provider>
You can pass an object inside the value in the context provider, in other word you can pass the toggle function inside your value to be consumed in the childern. thus you gain an access to change your mode state.
Note that the way changes are determined can cause some issues when passing objects as value, this might trigger unnecessary rerendering see Caveats for more info. or refer to the useContext docs
<ColorModeContext.Provider
value={{ colorMode: colorMode, toggleColorMode: toggleColorMode }}
>
<ThemeProvider theme={theme}>
<Header />
</ThemeProvider>
</ColorModeContext.Provider>

how to change only current component style on hover

I have a requirement where I need to highlight the component on hover
I have two styles defined baseStyle and highlight
<div style={{ background: '#fff' }}>
<div
onMouseEnter={(e) => setToolStyle({ ...baseStyle, ...highlight })}
onMouseLeave={e => setToolStyle(baseStyle)}
style={toolStyle}>
<FontAwesomeIcon icon={faMousePointer} style={{ fontSize: "20px" }} />
</div>
<div
onMouseEnter={(e) => setToolStyle({ ...baseStyle, ...highlight })}
onMouseLeave={e => setToolStyle(baseStyle)}
style={toolStyle}>
<FontAwesomeIcon icon={faMousePointer} style={{ fontSize: "20px" }} />
</div>
</div>
Expected Output:
on hovering any of the component only that component must be highlighted(i.e just need to add highlight css class to it).
but right now all the component is getting highlighted because of toolStyle state. can anyone help me on this by giving some logic.
Here is an example
you can create a small component with the highlight effect
and use it component any number of times and from anywhere
(As I said in comments )
https://codesandbox.io/s/laughing-mclaren-4i8en?file=/src/highlight.js
child.js
import { useState } from "react";
const baseStyle = { color: "black", fontSize: 14 };
const highlight = { color: "red" };
export default function Highlight({ text }) {
const [toolStyle, setToolStyle] = useState(baseStyle);
return (
<div
onMouseEnter={(e) => setToolStyle({ ...baseStyle, ...highlight })}
onMouseLeave={(e) => setToolStyle(baseStyle)}
style={toolStyle}
>
{text}
</div>
);
}
parent.js
import Highlight from "./highlight";
import "./styles.css";
export default function App() {
return (
<div>
<Highlight text="text 1" />
<Highlight text="text 2" />
<Highlight text="text 3" />
</div>
);
}
This is the best way to implement this with code reusability and
less of code duplication
You can do something like this:
export default function App() {
let [hovered, setHovered] = React.useState({ div1: false, div2: false });
return (
<div>
<div
className={hovered.div1 ? 'hovered' : ''}
onMouseEnter={(e) => setHovered((ps) => ({ ...ps, div1: true }))}
onMouseLeave={(e) => setHovered((ps) => ({ ...ps, div1: false }))}
>
Hello
</div>
<div
className={hovered.div2 ? 'hovered' : ''}
onMouseEnter={(e) => setHovered((ps) => ({ ...ps, div2: true }))}
onMouseLeave={(e) => setHovered((ps) => ({ ...ps, div2: false }))}
>
Hello
</div>
</div>
);
}
You can move your styles to CSS file and avoid extra complexity:
App.js
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faCoffee } from "#fortawesome/free-solid-svg-icons";
import "./App.css";
function App() {
return (
<div className="wrapper">
<div>
<FontAwesomeIcon icon={faCoffee} />
</div>
<div>
<FontAwesomeIcon icon={faCoffee} />
</div>
</div>
);
}
export default App;
App.css
.wrapper {
background: #fff;
}
.wrapper > div {
color: red;
font-size: 20px;
}
.wrapper > div:hover {
color: green;
cursor: pointer;
}

React: How to combine multiple external makestyle using material ui?

I have multiple external makestyle that I want to combine. So, I can organize the style per component. The single makestyle is also good but the length of the file is too much.
I saw this on material ui documentation but it's not working
Makestyle
import useStyles from '../styles/style';
import useAddTaskStyles from '../styles/addTaskStyle';
const classes = useStyles();
const classesAddTask = useAddTaskStyles();
const className = clsx(classes, classesAddTask);
<Modal
className={className.modalContainer}
open={showAddTask}
onClose={handleCloseAddTask}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={showAddTask}>
<Tasks ref={useRef} />
</Fade>
</Modal>
import useStyles from '../styles/style';
import useAddTaskStyles from '../styles/addTaskStyle';
const classes = useStyles();
const classesAddTask = useAddTaskStyles();
<Modal
className={`${classes.modalContainer} ${classesAddTask.modalContainer}`}
open={showAddTask}
onClose={handleCloseAddTask}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={showAddTask}>
<Tasks ref={useRef} />
</Fade>
</Modal>;
You may combine it like this
const className = { ...classes, ...classesAddTask }
Codesandbox => https://codesandbox.io/s/nice-fire-xgvz2?file=/src/App.js
For Example (creating a useStyle hook that combines all style hooks)
import { makeStyles } from "#material-ui/styles";
const useStyles1 = makeStyles({
red: {
backgroundColor: "red"
}
});
const useStyles2 = makeStyles({
blue: {
backgroundColor: "blue"
}
});
const useStyles = () => {
const classes = useStyles1();
const classes2 = useStyles2();
return { ...classes, ...classes2 };
};
export default function App() {
const classes = useStyles();
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div className={classes.blue} style={{ width: "200px", height: "200px" }}>
blue box
</div>
<div className={classes.red} style={{ width: "200px", height: "200px" }}>
red box
</div>
</div>
);
}

Button components inside ButtonGroup

I'm using React 16.9.0 and Material-UI 4.4.2 and I'm having the following issue.
I want to render a ButtonGroup with Button elements inside it but these buttons come from other custom components which return a Button render with a Modal view linked to the button. Thing is, I can't make them look like a ButtonGroup with the same style since it seems like the Button elements only take the "grouping" styling but not the "visual" styling.
Example code to reproduce behaviour:
<ButtonGroup variant="outlined">
<AModal/>
<BModal/>
<CModal/>
</ButtonGroup>
As you can see, the render output does not look as expected. Bare in mind that I'm defining the buttons with the outlined variant since if not they just render as Text Buttons.
Any help is much appreciated
Adding AModal as requested:
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import { Button } from '#material-ui/core';
import Modal from '#material-ui/core/Modal';
import Backdrop from '#material-ui/core/Backdrop';
import Fade from '#material-ui/core/Fade';
import InnerModalComponent from './InnerModalComponent';
const useStyles = makeStyles((theme) => ({
modal: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
paper: {
backgroundColor: theme.palette.background.paper,
border: '2px solid #000',
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
export default function AModal() {
const classes = useStyles();
const [open, setOpen] = React.useState(false);
function handleOpen() {
setOpen(true);
}
function handleClose() {
setOpen(false);
}
return (
<div>
<Button variant="contained" onClick={handleOpen}> A </Button>
<Modal
aria-labelledby="transition-modal-title"
aria-describedby="transition-modal-description"
className={classes.modal}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{ timeout: 500 }}
>
<Fade in={open}>
<div className={classes.paper}>
<div
style={{
display: 'flex',
flexDirection: 'row',
alignItems: 'stretch',
justifyContent: 'center',
}}
>
<InnerModalComponent/>
</div>
<Button variant="contained" color="secondary" style={{ marginTop: '10px' }}> Button inside Modal</Button>
</div>
</Fade>
</Modal>
</div>
);
}
There are two main issues:
You are adding a div around each of your buttons. This will interfere a little with the styling. Change this to a fragment (e.g. <> or <React.Fragment>) instead.
The way that ButtonGroup works is by cloning the child Button elements and adding props to control the styling. When you introduce a custom component in between, you need to pass through to the Button any props not used by your custom component.
Here is a working example:
import React from "react";
import ReactDOM from "react-dom";
import ButtonGroup from "#material-ui/core/ButtonGroup";
import Button from "#material-ui/core/Button";
import Modal from "#material-ui/core/Modal";
const AModal = props => {
return (
<>
<Button {...props}>A</Button>
<Modal open={false}>
<div>Hello Modal</div>
</Modal>
</>
);
};
const OtherModal = ({ buttonText, ...other }) => {
return (
<>
<Button {...other}>{buttonText}</Button>
<Modal open={false}>
<div>Hello Modal</div>
</Modal>
</>
);
};
// I don't recommend this approach due to maintainability issues,
// but if you have a lint rule that disallows prop spreading, this is a workaround.
const AvoidPropSpread = ({
className,
disabled,
color,
disableFocusRipple,
disableRipple,
fullWidth,
size,
variant
}) => {
return (
<>
<Button
className={className}
disabled={disabled}
color={color}
disableFocusRipple={disableFocusRipple}
disableRipple={disableRipple}
fullWidth={fullWidth}
size={size}
variant={variant}
>
C
</Button>
<Modal open={false}>
<div>Hello Modal</div>
</Modal>
</>
);
};
function App() {
return (
<ButtonGroup>
<AModal />
<OtherModal buttonText="B" />
<AvoidPropSpread />
</ButtonGroup>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

material-ui button active style

I am trying to workout how I would have appbar buttons that link to components show a different style when active.
I should also note: this is a my first material-ui app and the docs are not so clear.
Basically I want an underline on the button that is active.
<Button color="inherit" component={Link} to={"/"}>Home</Button>
<Button color="inherit" component={Link} to={"/About"}>About</Button>
My full code.
import React, {useState } from 'react';
import { Link as Links } from 'react-router-dom';
import ReactDOM from 'react-dom';
import { makeStyles } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Fab from '#material-ui/core/Fab';
//import Icon from '#material-ui/core/Icon';
import Toolbar from '#material-ui/core/Toolbar';
import Link from '#material-ui/core/Link';
import Typography from '#material-ui/core/Typography';
import Button from '#material-ui/core/Button';
import IconButton from '#material-ui/core/IconButton';
import MenuIcon from '#material-ui/icons/Menu';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
fab: {
position: 'absolute',
background:'red',
bottom: theme.spacing(2),
right: theme.spacing(2),
"&:hover, &:focus":{
background:'black',
}
},
title: {
flexGrow: 1,
align:'center',
},
}));
function Nav() {
const classes = useStyles();
const [icon,setIcon] = useState(false)
const fabIcon = {
color: 'white',
fontSize: 40,
};
const handleClick = e => {
setIcon(!icon)
{ icon ? document.getElementById("player").play() : document.getElementById("player").pause() }
}
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="Menu">
<MenuIcon />
</IconButton>
<Typography variant="h6" align="center" className={classes.title}>
News
</Typography>
<Button color="inherit">Login</Button>
<Button color="inherit" component={Links} to={"/"} linkButton={true}>Home</Button>
<Button color="inherit" component={Links} to={"/about"}>About</Button>
</Toolbar>
</AppBar>
<AppBar position="static">
</AppBar>
<audio id="player">
<source
src="https://samcloud.spacial.com/api/listen?sid=106487&m=sc&rid=184639"
type="audio/mpeg"
/>
</audio>
<Fab aria-label='test' className={classes.fab}>
<i className='large material-icons' style={fabIcon} onClick={handleClick}>
{ icon ? 'play_circle_outline' : 'pause_circle_outline'}</i>
</Fab>
</div>
);
}
export default class GrandChild extends React.Component {
componentDidMount() {
setTimeout(function(){ document.getElementById("player").play() }, 3000);
}
value() {
return ReactDOM.findDOMNode(this.refs.input).value;
}
render() {
return (
<div>
<Nav />
</div>
);
}
}
I recently had the same issue, and I solved it by using NavLink instead of Link from react-router-dom!
Example:
<Button
className={classes.button}
component={NavLink}
to="/page-link"
>
This will add the class ".active" to active buttons.
Using material's makeStyles hook, you can then style the buttons with this class:
const useStyles = makeStyles({
button: {
"&.active": {
background:'black',
},
},
});
If you're not using any third-party library like Gatsby, React-router then you should consider about this Tabs
Code:
import React from 'react';
import { makeStyles, Theme } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import Typography from '#material-ui/core/Typography';
import Box from '#material-ui/core/Box';
interface TabPanelProps {
children?: React.ReactNode;
index: any;
value: any;
}
function TabPanel(props: TabPanelProps) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
function a11yProps(index: any) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
const useStyles = makeStyles((theme: Theme) => ({
root: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper,
},
}));
export default function SimpleTabs() {
const classes = useStyles();
const [value, setValue] = React.useState(0);
const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
setValue(newValue);
};
return (
<div className={classes.root}>
<AppBar position="static">
<Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
<Tab label="Item One" {...a11yProps(0)} />
<Tab label="Item Two" {...a11yProps(1)} />
<Tab label="Item Three" {...a11yProps(2)} />
</Tabs>
</AppBar>
<TabPanel value={value} index={0}>
Item One
</TabPanel>
<TabPanel value={value} index={1}>
Item Two
</TabPanel>
<TabPanel value={value} index={2}>
Item Three
</TabPanel>
</div>
);
}
To master in Material UI Tabs

Resources