Add conditional CSS property in React - html

I want to add conditional CSS property to a div in such a way that if particular condition is true then only it will applied. Below is my code.
const Select = ({
handleClick,
title,
permission,
}: SelectProps) => {
return (
<div
onClick={handleClick}
style={{
marginTop: '16px',
cursor: 'pointer',
pointerEvents <-- make this property conditional
${({ permission }) => permission && `pointerEvents: none;`} <-- tried this but not working
}}
>
<Title>{title}</Title>
</div>
);
};
export const RenderSelectBlock = () => {
const checkUserPermission = checkUserPermission();
return (
<Select
handleClick={() => setSelectType('Google')}
title="Google"
checkUserPermission={checkUserPermission}
/>
<Select
handleClick={() => setSelectType('Microsoft')}
title="Microsoft"
checkUserPermission={checkUserPermission}
/>
<Select
handleClick={() => setSelectType('Apple')}
title="Apple"
checkUserPermission={checkUserPermission}
/>
<Select
handleClick={() => setSelectType('Facebook')}
title="Facebook"
checkUserPermission={checkUserPermission}
/>
)
);
};
So here in the last Select where title is Facebook, I want to disable it if the user don't have permission i.e. permission = false. Basically pointerEvents property should only be added for title= Facebook and should be set to none if permission = false.

You best option is to avoid style entirely and use className, then include a second class (maybe no-pointer-events) for the pointer-events you want to optionally include:
<div
className={`main-class ${permission ? "no-pointer-events" : ""}`}
But if you want to do it with style, you could use undefined for when you don't want to specify it:
<div
style={{
marginTop: '16px',
cursor: 'pointer',
pointerEvents: permission ? "none" : undefined,
}}
You could also define the style object before reaching this point in the code:
const style = {
marginTop: '16px',
cursor: 'pointer',
};
if (permission) {
style.pointerEvents = "none";
}
Then use it:
<div
style={style}
Sometimes you'll see people do this with multiple properties via spread syntax:
<div
style={{
marginTop: '16px',
cursor: 'pointer',
...(permission ? {pointerEvents: "none"} : undefined),
}}
...undefined is fine in an object literal (it doesn't add any properties).

Related

How to Override MUI CSS in a React Custom Component which uses MUI Component in it?

Below is the Custome Component which i created in Reactjs and used in different component :
function SearchBox({ handle, placeholder, inputType, ...props}) {
return (
<Box
sx={{
display: 'flex',
alignItems: 'flex-end',
margin: 1,
marginTop: 0,
maxHeight: '30px'
}}
>
<TextField
sx={{
fontSize: '12px',
width: '100%'
}}
variant={inputType || 'standard'}
InputProps={{
startAdornment: (
<InputAdornment position='start'>
<SearchIcon
sx={{
color: 'action.active',
mb: 0.2,
display: 'flex',
alignItems: 'flex-end'
}}
/>
</InputAdornment>
),
placeholder: placeholder || 'Search'
}}
onChange={handle}
/>
</Box>
);
}
I am using this Component in Some Other Component <SearchBox handle={Keyword}/>
so how to override css for TexField and Box of the SearchBox component? i don't want to touch the SearchBox need to override css properties from the place where i am using this component.
When i did Inspect on the Browser i saw something like this <div class="MuiBox-root css-1uqe0j">...</div>
what is css-luqe0j ?
Can Anyone Help me out with this.
If you don't want to modify the SearchBox component at all, you have a few options, the most reasonable of which (IMO) is to just wrap the SearchBox component in a styled component that then targets elements contained within the SearchBox (it's child), for example:
const SearchBoxStyleOverrides = styled("div")({
".MuiBox-root": {
padding: "2rem",
backgroundColor: "green"
},
".MuiSvgIcon-root": {
color: "red"
},
".MuiInput-input": {
backgroundColor: "yellow"
}
});
export default function YourApp() {
return (
<SearchBoxStyleOverrides>
<SearchBox />
</SearchBoxStyleOverrides>
);
}
Which produces: (ugliness is for effect)
Working CodeSandbox: https://codesandbox.io/s/peaceful-dubinsky-wjthtt?file=/demo.js
And to answer your secondary question ("what is css-luqe0j ?"), that is the generated css class name for the component -- you don't want to target an element using those because they will frequently change.

Why input value does not change when we pass null or undefined as a value?

While working with the controlled input components if we set the value of the controlled component to null or undefined the previous value is still displayed on the UI instead of changing it and the state holding that input value changes to null or undefined. I have created a sandbox for better understanding
https://codesandbox.io/s/black-architecture-0wqw1
Thank you
If the data type is null or undefined react automatically supress that value and log nothing.
If you want to see the type of that particular value, write {typeof data}, then you'll get your answer.
...
setData(null)
typeof data // object
setData("hi")
typeof data // string
setData(undefined)
typeof data // undefined
...
here is quick fix, it never changes value variable, if data then put data else empty string, that how it works
<input
type="text"
onChange={(e) => setData(e.target.value)}
value={data ? data:""}
/>
i hope this will solve your problem,
here is complete fix,
https://codesandbox.io/embed/optimistic-currying-snn8t?fontsize=14&hidenavigation=1&theme=dark
You can use ref tout change the value of your input anywhere outside your input component, see bellow :
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [data, setData] = useState(null);
const inputRef = React.useRef(null);
useEffect(() => {
console.log(data);
}, [data]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input
ref={inputRef}
type="text"
onChange={(e) => setData(e.target.value)}
value={data}
/>
<div style={{ marginTop: "10px" }}>
<button onClick={() => {
setData(null);
inputRef.current.value = ''
}}>SET DATA NULL</button>
</div>
<div style={{ marginTop: "10px" }}>
<button onClick={() => {
setData(undefined)
inputRef.current.value = ''
}}>
SET DATA UNDEFINED
</button>
</div>
<div style={{ marginTop: "10px" }}>INPUT VALUE {data}</div>
</div>
);
}

Class is not applied to Material UI button component

I am trying to apply a class (redirectButton) to material UI button , but it is not getting applied.
here is my html
{(isDataAdapterAdmin && !dataSources?.length) &&
<Button className={classes.redirectButton} onClick={() => history.push('/settings_systems/dataSources')} >
{i18n._(buttonText)}
</Button>
}
const useStyles = makeStyles((theme: Theme) => ({
redirectButton:{
'display': 'flex',
'justify-content': 'center',
'margin-right': '400px'
}
}))
In output, the parent div is something like this
<div class>
If you want to apply the style to the root element you need to override classes:
Documentation here
classes={{ root: classes.redirectButton }}
// insted of
className={...}

css inline styles not applying to react table cells when using className

I'm trying to apply inline css to the react table cell, shown in the code by *** surrounding the div element. It works as it is declared right now, using Style=.... , but I would like to use className='textvertalign'instead, and when I try using className it doesn't seem to work. I can't seem to put my finger on why it doesn't work with className. It would be nice to be able to reference this css as I plan on applying it to more cells. Thanks in advance.
const styles = theme => ({
textvertalign:{
display:'flex', justifyContent:'center'
}
});
class UserManagement extends React.Component {
return
<div>
<ReactTable key={this.state.tablePageSize}
data={this.state.portalUsers}
filterable
defaultFilterMethod={filterCaseInsensitive}
columns={[{
columns: [{
Header: <div style={{ fontSize: '16px', textAlign: 'center', fontWeight: 'bold' }}>Edit</div>,
width: 90,
id: "Edit",
className: "align-center",
Cell: ({ row }) => (
***<div style={{display:'flex', justifyContent:'center'}}>***
<button className="FlatButton"
onClick={e => this.handleDialogOpen(e, row)}>
{
<FontAwesomeIcon style={{ color: '#FF3933' }} icon="edit" />
}
</button>
</div>
)
}....
</ReactTable>
</div>
}
UserManagement.propTypes = {
classes: PropTypes.object.isRequired,};
export default withStyles(styles)(UserManagement);
found the explanation and solution here: https://codex.happyfuncorp.com/styling-and-theming-with-material-ui-react-material-design-3ba2d2f0ef25
To be able to use the css that are in styles, I have to add:
const {classes} = this.props; //in render
className={classes.textvertalign} //to reference that css.
I think this has to do with the withStyles exporting the css, and we need to import it back in to use it.

How to implement custom Tab indicator color in Material-UI v1

I have MUI v1 beta 32 running on a production site, very nicely.
Time to update to v1!
So far, changes have been very simple. It's mostly been a matter of updating the import tags.
But I am running into an issue with my selected <Tab/> indicator.
I was using the rootInheritSelected style override in order to apply the color of my choice.
How to implement it in v1?
In the end I found it was much simpler:
<Tabs
textColor="inherit"
fullWidth
centered
classes={{
indicator: classes.indicator
}}>
<Tab />
<Tab />
</Tabs>
and the styles:
const styles = theme => ({
indicator: {
backgroundColor: 'white',
},
})
I was able to do this with the TabIndicatorProps.
Example:
<Tabs
value={this.state.value}
onChange={(event, newValue) => {
this.setState({value: newValue})
}}
TabIndicatorProps={{
style: {
backgroundColor: "your_custom_color"
},
}}
>
This allowed me to also add different indicator colors based on what tab is active