I’m trying to create a survey page using Material UI in React. I’d like my survey to turn on when the user scrolls over a question and turns off when the user scrolls out of a question. A behavior similar to this page.
https://www.surveymonkey.com/r/Typical-Customer-Demographics-Template
After doing some research, I decided to use useScrollTrigger module in MUI. I was able to turn on the questions when I scroll down to them, but still can’t figure out a way to turn them back off when I scroll down, out of them.
This is how I created my scrollToColor function:
import { useScrollTrigger } from "@material-ui/core";
export default function ScrollToColor(props) {
const {
threshold,
threshold2,
textColorBefore,
textColorAfter,
fadeIn,
fadeOut,
children,
...other
} = {
threshold: 50,
threshold2: 100,
textColorBefore: "gray",
textColorAfter: "black",
fadeIn: "0.1s ease-in",
fadeOut: "0.1s ease-out",
...props,
};
const trigger = useScrollTrigger({
disableHysteresis: true,
threshold: threshold,
target: props.window ? window() : undefined,
});
const trigger2 = useScrollTrigger({
disableHysteresis: true,
threshold: threshold2,
target: props.window ? window() : undefined,
});
return React.cloneElement(children, {
style: {
color: trigger ? textColorAfter : textColorBefore,
transition: trigger ? fadeIn : fadeOut,
color: trigger2 ? textColorBefore : textColorAfter,
transition: trigger2 ? fadeOut : fadeIn,
},
...other,
});
}
I created 2 triggers so when it scrolls to the question, the text color turns black and when scroll out, it turns back to gray. This is a sample code on how I added this to the parent component.
import {
AppBar,
Toolbar,
Typography,
ThemeProvider,
CssBaseline,
createMuiTheme
} from "@material-ui/core";
import ScrollToColor from "./ScrollToColor";
const NavbarscrollToColor = props => {
const theme = createMuiTheme();
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<ScrollToColor>
<AppBar position="static">
<Toolbar>
<Typography variant="h5" noWrap>
{props.title}
</Typography>
</Toolbar>
</AppBar>
</ScrollToColor>
</ThemeProvider>
);
};
export default NavbarscrollToColor;
But this unfortunately doesn’t work. Any tips on how to make this work?
Also, is there any easier and cleaner way in React I could have archived this other than using the MUI useScrollTrigger module?
Thanks!