How to pass dynamic values to ReactJS JSS? - css

I need to pass dynamic values to linear-gradient in such a way shown below. How would I do this? I have tried implementing the small example of Dynamic Values on the cssinjss web site without success.
const useStyles = createUseStyles({
card:{
background: 'linear-gradient(to top, orange, rgb(to top, 255, props.green, 0))',
width: '200px',
height: '240px',
margin: '50px',
display: "flex",
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
color: 'white',
fontFamily: 'arial',
padding: 6,
borderRadius: 15,
composes: 'shadow'
}
});
const WeatherCard = (props) => {
const classes = useStyles(props);
return (
<div>
<div className={classes.card}>
<Location />
<Icon />
<Tempature />
</div>
</div>
);
};
WeatherCard.defaultProps = {
green: 125
};

Your code is correct, just missing the callback that tells the variable props with the values, try the following:
See in: https://cssinjs.org/react-jss/?v=v10.4.0#dynamic-values
const useStyles = createUseStyles({
card:{
background: props => `linear-gradient(to top, orange, rgb(to top, 255, ${props.green}, 0))`,
width: '200px',
height: '240px',
margin: '50px',
display: "flex",
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
color: 'white',
fontFamily: 'arial',
padding: 6,
borderRadius: 15,
composes: 'shadow'
}
});
const WeatherCard = (props) => {
const classes = useStyles({...props});
return (
<div>
<div className={classes.card}>
<Location />
<Icon />
<Tempature />
</div>
</div>
);
};

If it’s just one spot to put dynamic values, I would just inline style it. I understand that things need to be “perfect”, but inline styling is totally legitimate, I would use template literals as well.
So let’s say I have a component that I take a prop from.
function foo ({ green }) {
return <div style='background:${green}'></div>
}
I used the curly brackets so I don’t need the props keyword, it understands I’m trying to grab the variable name.

Related

In ReactNative for web, how do I apply my stylesheet to the slider and thumb of the type="range" <input > element?

I have a component that is an audio slider (the built in one was deprecated), to modify the range of the volume. It has a bug that the slider and thumb are always blue, and we need green. There is a stylesheet with the styles for each part of the component. When I try to apply the stylesheet to the '< input >' element, I get an error:
Error: Minified React error #62; visit https://reactjs.org/docs/error-decoder.html?invariant=62&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
which says:
The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.
In all the other core components (see this list about ReactNative
View style props
the applied style.XXX works. But the '< input >' tag is not listed as a ReactNative element, so it seems I have to use a different method to style it.
Here is the code:
const AudioSlider: FC<any> = (props: any) => {
const {audioCategory, activeSlider, setActiveSlider, setVolume, volume} =
props;
return (
<View style={style.AudioSliderContainer} key={audioCategory}>
<Pressable
style={
activeSlider == audioCategory
? [
style.SliderContainer,
{borderColor: $config.PRIMARY_COLOR || '#0A8C4A'},
]
: style.SliderContainer
}
onPressIn={() => setActiveSlider(audioCategory)}>
<Text style={style.SliderText}>Max</Text>
<input
type={'range'}
className="AudioSliderInput"
style={style.AudioSliderInput}
onChange={(e) => setVolume(audioCategory, e.target.value)}
value={volume}
/>
</Pressable>
<Text style={style.AudioSliderText}>{audioCategory || 'Audio'}</Text>
</View>
);
};
and the stylesheet:
export default AudioSlider;
const style = StyleSheet.create({
AudioSliderContainer: {
width: 56,
height: 175,
justifyContent: 'center',
alignItems: 'center',
marginHorizontal: 5,
},
AudioSliderInput: {
width: 100,
height: 30,
transform: 'rotate(-90deg) translateX(37px)',
borderRadius: 0,
backgroundColor: '#0A8C4A',
},
AudioSliderText: {
width: '100%',
fontFamily: 'Eurostile',
fontWeight: 'bold',
fontSize: 10,
color: $config.SECONDARY_FONT_COLOR || '#FFFFFF',
paddingTop: 10,
paddingBottom: 5,
textAlign: 'center',
display: 'flex',
justifyContent: 'center',
},
SliderContainer: {
width: '100%',
height: 'calc(100% - 30px)',
backgroundColor: '#373737',
borderRadius: 6,
justifyContent: 'space-between',
alignItems: 'center',
padding: 10,
paddingTop: 5,
borderColor: 'transparent',
borderWidth: 1,
borderStyle: 'solid',
},
SliderText: {
fontFamily: 'Eurostile',
fontWeight: 'bold',
fontSize: 9,
color: $config.SECONDARY_FONT_COLOR || '#FFFFFF',
textAlign: 'center',
paddingVertical: 5,
width: '100%',
marginRight: -2,
},
});
In my research, I found that I will also need to "cancel" the default styles for the input type="range" element using -webkit- properties, which are not recognized.
Questions:
Why the style prop is being interpreted as a string instead of a Javascript object that has the requested mappings of prop:value?
Should I switch to an external css file and import it, for the < input > element? or use style.components (which are not used elsewhere) or inline CSS perhaps?
How to be able to use -webkit-appearance: none; as part of the style?
If I have to throw everythign out and start over just to get green, which community slider should I use? Many seem to have loads of unclosed issues?
Many thanks!

How to place icon at the end in linear progress bar MUI?

I'm using MUI v5 to build linear progress bar.I have a scenario where if value in progress bar is 100%,I need to show tick icon at the end.The width of the bar with/without tick icon should be same,meaning icon shouldn't be placed after the bar.It should be at the end of bar.I tried with stylings and able to place tick icon at the end.But I'm unable to show the icon clearly as the bar overlaps with tick icon.
<div style={{ display: "flex", flexDirection: "row", position: "relative", alignItems: "center" }}>
<LinearProgress
variant="determinate"
sx={{
width: "100%",
borderRadius: "4px"
}}
value={50}
/>
<CheckCircleIcon sx={{ color: "blue" }} style={{ position: "absolute", width: "20px", display: "flex", justifyContent: "flex-end", right: "-2px", color: "#fff", fontWeight: "bold" }} />
</div>
Current Design
Expected Design
Here is a live demo where I've customized an MUI Slider with a checkmark SliderThumb.
The demo includes the foundation for using this as a progress bar:
Disable the slider to ignore user input. Keep in mind that disabling will change the color to gray. You can override disabled behavior through .Mui-disabled
Set the slider's value using a state variable that corresponds to your current progress
You may also choose to customize a LinearProgress component in the same way I've customized the Slider above. See the docs for LinearProgress customization.
Full slider code:
import * as React from 'react'
import Slider, { SliderThumb } from '#mui/material/Slider'
import { styled } from '#mui/material/styles'
import Box from '#mui/material/Box'
import CheckCircleIcon from '#mui/icons-material/CheckCircle'
const CheckMarkSlider = styled(Slider)(({ theme }) =>
({
color: '#3a8589',
height: 3,
padding: '13px 0',
'& .MuiSlider-thumb':
{
height: 20,
width: 20,
backgroundColor: '#fff',
border: '1px solid currentColor',
'&:hover': {
boxShadow: '0 0 0 8px rgba(58, 133, 137, 0.16)',
},
'& .checkmark-bar':
{
height: 9,
width: 1,
backgroundColor: 'currentColor',
marginLeft: 1,
marginRight: 1,
},
},
'& .MuiSlider-track':
{
height: 3,
},
'& .MuiSlider-rail':
{
color: theme.palette.mode === 'dark' ? '#bfbfbf' : '#d8d8d8',
opacity: theme.palette.mode === 'dark' ? undefined : 1,
height: 3,
},
}))
const CheckMarkThumbComponent = (props) =>
{
const { children, ...other } = props
return (
<SliderThumb {...other}>
{children}
<CheckCircleIcon />
</SliderThumb>
)
}
const CustomizedSlider = () =>
{
const [value, setValue] = React.useState(20)
React.useEffect(() =>
{
const intervalId = setInterval(() => setValue(Math.random() * 100), 500)
return () => clearInterval(intervalId)
}, [value])
return (
<Box sx={{ width: 320 }}>
<CheckMarkSlider
value = {value}
disabled
components={{ Thumb: CheckMarkThumbComponent }} />
</Box>
)
}
export default CustomizedSlider

Conditionally applying css not working in React JS using Typescript

I have the following code whereas onclick I should make the Box stay highlighted with the black border.
interface BigButtonProps {
onClick(): void;
Title: string;
Description?: string;
startIcon?: React.ElementType;
}
const BigButton: FC<BigButtonProps> = (props: BigButtonProps, { active }) => {
const [isClicked, setClicked] = useState(false);
const clickMe = () => {
setClicked(!isClicked);
console.log("say hello");
};
const SvgIconStyles: CSS.Properties = {
display: "block",
};
const BoxStyles: CSS.Properties = {
border: "1.5px solid black",
};
const BoxStylesActive: CSS.Properties = {
border: "1.5px solid black",
};
return (
<Box
sx={{
height: {
xs: "45px",
md: "100px",
},
width: {
xs: "45px",
md: "300px",
},
borderRadius: "10px",
boxShadow: "0 2px 3px 2px rgba(0, 0, 0, .125)",
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
":hover": {
border: "1.5px solid blue",
},
}}
className={classNames("BoxStyles", { BoxStylesActive: isClicked })}
onClick={() => {
clickMe();
}}
>
<Typography variant="h1">{props.Title}</Typography>
<Typography variant="subtitle1">{props.Description}</Typography>
<SvgIcon
component={CheckCircleIcon}
sx={{
display: "block",
}}
/>
</Box>
);
};
export default BigButton;
When I click on the button it should change the border color to solid black. When I do CSS active it does change on click but doesn't remain changed to black. So I have to apply CSS conditionally so I did create the CSS methods with the property type CSS.Properties; I'm using typescript and this is a react component I'm working on with. I'm not really sure what am I doing wrong here?
You can try something like
<Box styles={isClicked ? BoxStylesActive : BoxStyles}>
// ...
Notice that BoxStylesActive and BoxStyles are the same in your pasted code. So don't be surprised if you see no changes.
<Box sx={{border: isClicked ? "1.5px solid black" : none}}>
// ...
This can be used alternatively.
You are mixing sx prop and styles here. Also your BoxStylesActive is an object and no css class. So using classNames() won't have an effect on it.

React- Conditionally applying css in div but it does not work

Have looked at other examples and trying to do the same thing but not sure why my code is not working. I have code which loops through some keys and renders a div. I want to conditionally apply some styles based on whether the key is even or odd. Example:
<div className={parseInt(key) % 2 === 0 ? 'label1' : 'label2' }>
<span style={{ marginLeft: "10px" }}>{key}:00</span>
</div>
The styles are accessible in the same file and look something like:
# Material UI
const useStyles = makeStyles((theme) => ({
label1: {
width: "50px",
height: "16px",
top: "458px",
background: "yellow",
fontSize: "12px",
},
label2: {
width: "50px",
height: "16px",
top: "458px",
background: "red",
fontSize: "12px",
},
}));
What am I doing wrong? Currently no style is getting applied to the div
You need to use the classes from the material ui useStyles hook.
const classes = useStyles()
....
<div className={parseInt(key) % 2 === 0 ? classes.label1 : classes.label2 }>
<span style={{ marginLeft: "10px" }}>{key}:00</span>
</div>
Check the useStyles hook api: https://material-ui.com/styles/basics/
If you have a class component and you can use hooks then you can do it with the withStyles higher order component, like this example:
import { withStyles } from "#material-ui/core/styles"
const styles = theme => ({
label1: {
backgroundColor: "red",
},
label2: {
backgroundColor: "red",
},
})
class ClassComponent extends Component {
state = {
searchNodes: "",
}
render() {
const { classes } = this.props
return (
<div className={parseInt(key) % 2 === 0 ? classes.label1 : classes.label2}>
<span style={{ marginLeft: "10px" }}>{key}:00</span>
</div>
)
}
}
export default withStyles(styles, { withTheme: true })(ClassComponent)

React Select adjust the first option layout

I'm trying to adjust the first option to be centered in the option in the React Select but nothing it is working for that ( all other adjustments in the CSS of React Select it is working). here the code that I'm using in the option values:
const option = (provided, state) => ({
...provided,
background: state.isSelected ? theme.colors.green600 : theme.colors.white,
color: state.isSelected ? theme.colors.white : theme.colors.grey500,
display: 'flex',
fontFamily: 'CircularStd',
lineHeight: '18px',
fontSize: '14px',
':nth-child(0) ': {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
textTransform: 'uppercase',
},
});
obs: the option it is inside of customStyles, and I'm passing into the Select, like styles={customStyles}
In order to style the first option you may want to target the :first-child of the MenuList. Here is the example
const styles = {
menuList: (provided, state) => {
return {
...provided,
"& :first-child": {
textAlign: "center"
}
};
}
};
Live Example

Resources