How to focus Material UI Textfield upon opening a modal? - reactjs

If I autofocus the textfield, it loses focus once I click into the modal.
I place the modal here
<NewOrgModal open={open} handleClose={handleClose} />
<Drawer
variant='permanent'
sx={{
display: { xs: 'none', sm: 'block' },
'& .MuiDrawer-paper': {
boxSizing: 'border-box',
width: 110,
// backgroundColor: '#0f041c',
backgroundColor: '#180D24',
},
overflow: 'scroll',
}}
open
>
And the TextField is in the Modal
<Modal
sx={{ position: 'absolute', top: '33%', left: '33%' }}
open={open}
onClose={handleClose}
>
<Card
sx={{
width: 600,
height: 300,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Typography marginBottom={3} variant='h4' fontWeight='600'>
Create Org
</Typography>
<TextField
onKeyDown={(e) => (e.key === 'Enter' ? createOrg() : null)}
id='orgName'
onChange={(e) => setOrgName(e.target.value)}
value={orgName}
sx={{
width: 300,
input: { textAlign: 'center', padding: 1, fontSize: 20 },
}}
placeholder='My Awesome Org šŸ™‚'
/>
<Button
variant='contained'
onClick={createOrg}
sx={{
marginTop: 2,
borderRadius: 0,
boxShadow: 'none',
width: 300,
fontSize: 16,
fontWeight: 600,
}}
>
Submit
</Button>
</Card>
</Modal>
Is there a way to keep the textfield focused after clicking the button that opens the modal? If so, would there be any repercussions on having the textfield continue to focus after a specific action? e.g if I were to have other textfields in the future, would I need to think about other ways to not force the focus on the textfield in the modal?

You can autofocus on text field like this:
<TextField autoFocus></TextField>

You can use ref and on the modal open action, you can do ref.current.focus() like this. try this way once

Related

how to make 3 mui textfields under single border in react js

I want to add dimensions box. i created 3 mui textfields under formGroup and make border radius:0 and changed colour properties still it didn't work.
This what i want
I want to make 3 input fields in single border roof with attached autoComplete at the end. autoComplete want to look same as Mui textfield's width and height.
To remove the border of an input you should change it's border-width.
And for the cross signs you can use MUI icons.
So you will have a Box with flex display, that has 3 TextFields, 2 Icons and 1 Autocomplete inside.
This will be your final code:
import { TextField, Autocomplete, Box } from "#mui/material";
import CloseIcon from "#mui/icons-material/Close";
function Test() {
return (
<Box
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "240px",
border: "1px solid grey",
direction: "ltr",
}}
>
<TextField
size="small"
sx={{ width: "50px", "& fieldset": { borderWidth: 0 } }}
/>
<CloseIcon sx={{ fontSize: "10px" }} />
<TextField
size="small"
sx={{ width: "50px", "& fieldset": { borderWidth: 0 } }}
/>
<CloseIcon sx={{ fontSize: "10px" }} />
<TextField
size="small"
sx={{ width: "50px", "& fieldset": { borderWidth: 0 } }}
/>
<Autocomplete
disableClearable
size="small"
options={["cm", "inch"]}
renderInput={(params) => (
<TextField
{...params}
sx={{
backgroundColor: "#f5f5f5",
"& fieldset": { borderRadius: 0 },
}}
/>
)}
sx={{ width: "70px" }}
/>
</Box>
);
}
export default Test;

How to change color in Stepper according to active and completed Step

Reactjs,MaterialUI
I am using reactjs and material ui in my project and i want to change color of StepConnector and Button inside Step if it is active or completed.i want to change color of StepConnector and Button if next step is Active.Below is the code i am using:
const Cart = () => {
return (
<Box
sx={{
minHeight: "800px",
bgcolor: "#F6F9FC",
width: "100%",
}}
>
<Stepper
nonLinear
activeStep={activeStep}
sx={{
maxWidth: "60%",
marginLeft: "10%",
"& .MuiStepConnector-line": {
borderColor: "#085E7D",
borderTopWidth: "4px",
minWidth: "30px",
},
}}
>
{steps.map((label, index) => (
<Step key={label} sx={{ padding: "0px" }}>
<Button
variant="contained"
onClick={handleStep(index)}
completed={completed[index]}
sx={{
bgcolor: "#085E7D",
borderRadius: "25px",
"&:hover": {
backgroundColor: "#085E7D",
boxShadow: "none",
textShadow: "none",
margin: "0px",
},
}}
>
{label}
</Button>
</Step>
))}
</Stepper>
</Box>
);
};
export default Cart;
Please help me in my code..
Your code snippet doesn't really give enough context to fully answer your question (not sure how the buttons are working?). However if I use this example from the MUI website, the following change to the Stepper results in the connector lines changing color when the next step is "active" and "complete".
<Stepper
activeStep={activeStep}
sx={{
"& .MuiStepConnector-line": {
borderTopWidth: "4px",
},
"& .MuiStepConnector-root.Mui-active .MuiStepConnector-line": {
borderColor: "red",
},
"& .MuiStepConnector-root.Mui-completed .MuiStepConnector-line": {
borderColor: "green",
},
}}
>

Toolbar container to observe minWidth

I'm new to react and material UI and I've been trying to design my navbar so that my logo, search bar and drawer are in the center. I was able to get help earlier to get space between the components and have my search bar centered, but now i'm struggling to have my logo and drawer to be in the center while observing a minimum width from my searchbar.
I already tried wrapping them into a container with a specified width but they lose their alignment in the center.
here's my code:
const Search = styled('div')(({ theme }) => ({
position: 'relative',
borderRadius: 30,
backgroundColor: alpha(theme.palette.common.white, 0.15),
'&:hover': {
backgroundColor: alpha(theme.palette.common.white, 0.25),
},
// marginLeft: 10,
width: 'auto'
}));
const SearchIconWrapper = styled('div')(({ theme }) => ({
padding: theme.spacing(0, 2),
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}));
const StyledInputBase = styled(InputBase)(({ theme }) => ({
color: 'inherit',
'& .MuiInputBase-input': {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(4)})`,
transition: theme.transitions.create('width'),
width: 'auto',
},
}));
export default function SearchAppBar({ search, setSearch }) {
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="fixed" sx={{ backgroundColor: "#55597d" }}>
<Toolbar sx={{ justifyContent: "space-between" }}>
<Stack direction="row" alignItems="center">
<img
style={{ marginRight: "10px" }}
src={logo}
alt="logo"
className="logotext"
width="38"
height="38"
/>
</Stack>
<Search>
<SearchIconWrapper>
<SearchIcon />
</SearchIconWrapper>
<StyledInputBase
sx={{ width: "auto" }}
value={search}
onChange={(e) => {
setSearch(e.target.value);
}}
placeholder="Search All Gamesā€¦"
inputProps={{ "aria-label": "search" }}
/>
</Search>
{/*</div>*/}
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="open drawer"
sx={{ mr: 0, ml: 0 }}
>
<MenuIcon />
</IconButton>
</Toolbar>
</AppBar>
</Box>
);
}

Material UI: I want to make this component responsive

I have this project and it is in order to monitor employees and I have a component which is "create workspace"
and I have added elements to this interface and I want this interface to be responsive, how can I do that?
And what are the ways in which you can make this page responsive?
Within this component, I have added a group of elements.
const useStyles = makeStyles({
resize:{
fontSize:24
}
});
const Settings: FC = () => {
const classes = useStyles()
return (
<Card style={{backgroundColor: 'transparent' , maxWidth: 1500 , minWidth: 500}}>
<CardContent>
<Box
sx={{
maxWidth: 1500,
// minWidth: 300
}}
>
<Box
sx={{
display: 'flex',
justifyContent: 'start'
}}
>
<Avatar style={{width: '5rem', height: '5rem'}} alt="Remy Sharp"
src="/static/images/avatar/1.jpg"/>
<TextField
fullWidth
name="workspaceName"
placeholder="Workspace Name"
variant="standard"
style={{
paddingLeft: '1.4rem',
transition: ' all .2s cubic-bezier(.785,.135,.15,.86) 0s',
display: 'flex',
alignItems: 'center',
flexGrow: 1,
position: 'relative',
color: '#828588',
}}
InputProps={{
classes: {
input: classes.resize,
},
}}
defaultValue="nameeeee"
/>
</Box>
</Box>
<CardActions
style={{ paddingTop: '10rem'}}
>
<Button style={{
minWidth: '10rem',
fontSize: '1.5rem',
height: '44px',
fontWeight: 400,
textShadow: 'none',
color: '#fd71af',
border: 0,
background: 'none'
}}>Delete Workspace</Button>
<Button
color="primary"
component={RouterLink}
to="/dashboard/workspaces/1"
variant="contained"
style={{
minWidth: '13rem',
minHeight: '4.3rem',
fontSize: '1.4rem',
backgroundColor: '#7b68ee',
borderRadius: 6,
marginLeft:'60rem'
}}
>
Saved
</Button>
</CardActions>
</CardContent>
</Card>
);
}
export default Settings;
Use material UI grids where ever you want to make the layout responsive. Check its documentation here : Material UI Grid
You can add different layouts for different screen sizes. You should also wrap your component in the Container component provided by Material-UI, It makes your web page fluid.
Hope this answers your question.

React.js -- input field -- losing focus when typing letters "c" or "n"

So I have an input field inside a MenuItem from MaterialUI, and that MenuItem is inside a Menu. For some strange reason, the input fields lose focus only when typing the letters "c" or "n".
Here is a picture of a Menu with an input field in it. I have noticed that when I type the letter "c", the focus changes from the input field to the first MenuItem, and I am really guessing it is because the inner text starts with the letter "c". (I would upload a gif of what is happening but stackoverflow says the gifs are too much memory to upload)
Since the input loses focus, the letter "c" does not even get typed into the input field. The focus just ends up on the MenuItem that has "Change Username" in it (I know this because it gets highlighted with a light grey color). It is the strangest thing and I cannot figure it out. I've even tried using a normal input tag instead of the Input from material-ui and it does the same thing.
Here is the code for the MenuItem with the input in it.
const changeCredentialsHandleChanges = (e:any) => {
e.persist();
const newCredentials = {...credentials, [e.target.name]: e.target.value}
setCredentials(newCredentials);
console.log(credentials);
if(newCredentials.newPassword === newCredentials.confirmNewPassword){
setChangePasswordButtonDisabled(false);
} else {
setChangePasswordButtonDisabled(true);
}
}
<MenuItem disableGutters classes={{root: profileMenuClasses.text2}}>
<div
style={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
borderBottom: '1px solid #F2F2F2',
minWidth: '100%',
maxHeight: '10px',
padding: '10px 0px 20px 15px'
}}
>
<div
style={{
cursor: 'pointer',
width: '20%',
maxHeight: '10px',
transform: 'scale(.7, .7)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
marginLeft: '-8%'
}}
onClick={changeUsernameHandleClick}
>
<ArrowBackIosIcon fontSize='small' color='action'/>
</div>
<p
style={{
width: '80%',
maxHeight: '10px',
color: '#000000',
fontWeight: 'bold',
fontSize: '11px',
marginBottom: '8%'
}}
>
Change Username
</p>
</div>
</MenuItem>
<MenuItem disableGutters classes={{root: profileMenuClasses.text2}}>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
borderBottom: '1px solid #F2F2F2',
minWidth: '100%',
whiteSpace: 'pre-line',
maxHeight: '50px'
}}
>
<p
style={{
color: '#000000',
width: '100%',
fontSize: '11px',
fontWeight: 600,
maxHeight: '12px',
margin: '0 0 0 5%'
}}
>
Current Username
</p>
<p
style={{
color: '#000000',
width: '100%',
fontSize: '10px',
margin: '3% 0 10% 5%',
maxHeight: '10px'
}}
>
{currentUser.username}
</p>
</div>
</MenuItem>
<MenuItem disableGutters classes={{root: profileMenuClasses.text2}}>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent:'center',
minWidth:'100%',
whiteSpace:'pre-line'
}}
>
<p
style={{
color: '#888888',
fontSize:'11px',
margin: '0 0 0 5%',
maxHeight: '10px'
}}
>
New Username
</p>
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<Input
key='newUsernameInput'
id='newUsername'
type='text'
classes={{input: profileMenuClasses.input}}
disableUnderline
placeholder='New Username'
name='newUsername'
value={credentials.newUsername}
onChange={changeCredentialsHandleChanges}
/>
</div>
<Button
style={{
width: '100px',
height: '26px',
margin: '7% 0 0 5%',
borderRadius: '15px',
fontSize: '11px',
backgroundColor: '#5540C7',
color: '#FFFFFF',
fontWeight: 600
}}
onClick={changeUsernameOnSubmit}
>
CONFIRM
</Button>
</div>
</MenuItem>
There are thousands of lines of code that I did not work on in this program (other than this Menu and a few other Menus(which have the same problem)), so my guess is that there is some block of code in this script that overrides the focus for this input field. Any thoughts, or a work-around perhaps ?
PS every other character can be typed into the input field without a problem, only the letters "c" and "n" have issues.
I had the same issue.
The easiest solution I found is to add zero-width non-breaking space symbol (ā ) in front of the text of MenuItems.
In my case it looks like this:
<MenuItem>
<Typography variant="body1">ā Columns</Typography>
</MenuItem>
Good:
text is not started from a letter that user can type from a keyboard
zero-width non-breaking space symbol has no effect on layout
Not so good:
you need to keep the special symbol in the markup

Resources