I'm trying to apply maxWidth to the TextField from material-ui but it seems like I can't.
import * as React from "react";
import Box from "#mui/material/Box";
import TextField from "#mui/material/TextField";
export default function BasicTextFields() {
const messages = [
{ id: 1, message: "short message" },
{
id: 2,
message: " It comes with three variants: outlined."
},
{
id: 3,
message:
"The TextField wrapper component is a complete form control including a label, input, and help text."
}
];
return (
<Box
component="form"
sx={{
"& > :not(style)": { m: 1, width: "25ch" }
}}
noValidate
autoComplete="off"
style={{ display: "flex", flexDirection: "column" }}
>
{messages.map((e) => (
<TextField
id="outlined-basic"
key={e.id}
value={e.message}
label="Outlined"
variant="outlined"
multiline={true}
style={{ maxWidth: "350px" }}
/>
))}
</Box>
);
}
Currently, the max-width for TextField seems not applying correctly. If I look at TextField with the inspect, it says 200px
I know I can apply regular width like this.
<TextField
id="outlined-basic"
key={e.id}
value={e.message}
label="Outlined"
variant="outlined"
multiline={true}
style={{ width: "350px" }}
/>
But what I want here is maxWidth.
Ideally, I like to have the width of text input based on the message length which I pass to the value property like this value={e.message}.
So before the width hits 350px, width needs to be kind of auto like the width is depends on the message, but once it hits 350px, it will keep being 350px.
Is that possible with the TextField component?
Attampts
I used InputProps proptery.
{messages.map((e) => (
<TextField
id="outlined-basic"
key={e.id}
value={e.message}
label="Outlined"
variant="outlined"
multiline={true}
InputProps={{
style: { maxWidth: "350px" }
}}
/>
))}
But I got width 200px.
if you wrap in an div?
<div style: { width: "400px" }>
<TextField
id="outlined-basic"
key={e.id}
value={e.message}
label="Outlined"
variant="outlined"
multiline={true}
InputProps={{
style: { maxWidth: "350px" }
}}
/>
</div>
Related
I am currently facing difficulties with React Mui's Autocomplete component. The Autocomplete is placed in a FormControl component.
In the renderInput prop of the Autocomplete, I added a TextField, but its label is being cut :
I tried playing with padding & margins, but it does not change anything and I do not know where the problem resides.
My code looks like this :
<Autocomplete
autoHighlight
value={value ?? null}
onChange={(event, newValue) => {
updateValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
sx={{ overflow: "hidden", whiteSpace: "pre-wrap", p: 0, m: 0 }}
options={displayedOptions}
getOptionValue={(option) => option?.optionValue ?? ""}
getOptionLabel={(option) => option?.optionLabel ?? ""}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
fullWidth
required={required}
label={label}
InputLabelProps={{ shrink: true }}
/>
)}
/>
As anyone faced this problem before ?
The problem is related to the styles.
From this sx prop:
sx={{ overflow: "hidden", whiteSpace: "pre-wrap", p: 0, m: 0 }}
You need to delete this part overflow: "hidden", so it should be like:
sx={{ whiteSpace: "pre-wrap", p: 0, m: 0 }}
I'm trying to include a DatePicker in my Bank page, after making a lot of search, and installation of all packages, I can't see what is happening, because the page is not rendering. I don't get any Errors after compiling. I just need a datePicker from Material ui, v.5.0 that's simple and easy to implement, like the basic usage: https://mui.com/x/react-date-pickers/date-picker/#basic-usage
I'm including my code below for correction, and please, if possible, give-me a check list, with step by step, to make this datePicker work. I need this in others pages, and I'm stuck. It seems confusing to implement, some how.
Thanks for your help.
import React, { useState } from 'react';
import { Container } from '#mui/material';
import { Typography } from '#mui/material';
import { Box } from '#mui/material';
import { TextField } from '#mui/material';
import { makeStyles } from '#mui/styles';
import { Button } from '#mui/material';
import KeyboardArrowRightIcon from '#mui/icons-material/KeyboardArrowRight';
import Grid from '#mui/material/Grid';
import { AdapterDateFns } from '#mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '#mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '#mui/x-date-pickers/DatePicker';
const useStyles = makeStyles((theme) => {
return{
root: {
display: "flex",
flexwrap: "wrap",
},
textField: {
margimLeft: theme.spacing(1),
margimRight: theme.spacing(1),
width: "25ch",
},
field: {
spacing: 2,
display: "block",
}
}
});
export default function Bancos(){
const classes = useStyles()
const [name, setName] = useState('')
const [address, setAddress] = useState('')
const [nameError, setNameError] = useState(false)
const [addressError, setAddressError] = useState(false)
const [value, setValue] = React.useState<Date | null>(null); // complaining in this final.
const handleSubmit = (e) => {
e.preventDefault()
setNameError(false)
setAddressError(false)
if(name == ''){
setNameError(true)
}
if( address == ''){
setAddressError(true)
}
}
const handleChange = (e) => {
}
return(
<Container>
<Typography variant="h6" color="textSecondary" align="center" gutterBottom
className="titleBank">
Cadastro de Bancos
</Typography>
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<Grid container spacing={2}>
<Box mt={3} mb={1}>
<Grid item xs={6} md={6}>
<TextField label="Nome do Banco" variant="outlined" color="secondary"
sx={{width: "430px", ml: 2}} required className={classes.field}
onChange={(e) => setName(e.target.value)} error={nameError}/>
</Grid></Box>
<Box mt={1}>
<Grid item xs={6} md={10} style={{ display: "flex" }}>
<TextField label="Endereço" variant="outlined" color="secondary"
sx={{width: "650px", mr: 1, ml: 2}} required className={classes.field}
onChange={(e) => setAddress(e.target.value)} error={addressError}/>
<TextField label="Bairro" className={classes.textField}
sx={{width: "350px" }} />
</Grid></Box>
<Grid item xs={6} md={10} style={{ display: "flex", margimLeft: 0}}>
<TextField label="Cidade" className={classes.field}
sx={{width: "320px", mr: 1 }} />
<TextField label="CEP" className={classes.field}
sx={{width: "180px", mr: 1}}/>
<TextField label="Contato" className={classes.field}
sx={{width: "350px", mr: 1 }} />
</Grid>
<Grid item xs={6} md={10} style={{ display: "flex", margimLeft: 0}}>
<TextField label="Telefone" className={classes.field}
sx={{width: "235px", mr: 1 }} />
<TextField label="E-mail" className={classes.field}
sx={{width: "350px", mr: 1 }} />
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</Grid><br/>
<Grid item xs={6} md={10} style={{ display: "flex", margimLeft: 0}}>
<TextField label="Nº Agência" className={classes.field}
sx={{width: "250px", mr: 1 }} />
<TextField label="Nº Conta Corrente" className={classes.field}
sx={{width: "300px", mr: 1 }} />
</Grid><br/>
<Grid item xs={6} md={8} style={{ display: "flex" }}>
<Box mt={4}>
<Button type="submit" variant="contained" color="primary"
endIcon={<KeyboardArrowRightIcon />}
>
Salvar
</Button>
</Box>
</Grid>
</Grid>
</form>
</Container>
)
}
strong text
I wrote code below to switch TextField and my custom component. But I can't set the height of the custom component with same height as TextField.
What can I do for this situation?
<Grid item xs={12}>
<FormControlLabel
control={<Switch value={toggleView} onChange={e => setToggleView(e.target.checked)} />}
label="view"
style={{position: 'absolute', top: `-4%`, right:'0', zIndex: '9999'}}/>
{
toggleView? <CustomComponent/> :
<TextField
rows="10"
multiline
fullWidth={true}
value={content}
onChange={e => setContent(e.target.value)}
label="content"
/>
}
</Grid>
you can change textFiled height and other properties in various ways like:
the sx prop:
<TextField
sx={{ '& .MuiOutlinedInput-root': { height: '50px' } }} // change height form here
variant="outlined"
/>
Mui styled component way(using emotion)
import { styled } from '#mui/material/styles'
import TextField from '#mui/material/TextField'
export const StyledTextField = styled(TextField)(() => ({
'& .MuiInputBase-root': {
height: 50
}
}))
Im Learning ReactJs ... I want Design a Form (Like Section Exprience in Linkedin) with React Hook Form, Material Ui and TypeScript.
I Faced a Error with this text: 'onChange' is specified more than once, so this usage will be overwritten.
my function in onChange, doesn't work. I want to register with react hook form. how can I solve this error?
import Typography from "#mui/material/Typography";
import TextField from "#mui/material/TextField";
import Box from "#mui/material/Box";
import { React, useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import Divider from "#mui/material/Divider";
import Select, { SelectChangeEvent } from "#mui/material/Select";
import MenuItem from "#mui/material/MenuItem";
import FormControl from "#mui/material/FormControl";
import InputLabel from "#mui/material/InputLabel";
// React Hook Form Types
type Inputs = {
title: string;
employment: string;
company: string;
location: string;
startDate: string;
endDate: string;
description: string;
};
function ExprienceCreate() {
const [employment, setEmployment] = useState("");
// React Hook Form
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm<Inputs>();
const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data);
// Function For Employment Type Select
const handleChange = (event: SelectChangeEvent) => {
setEmployment(event.target.value as string);
console.log(employment);
};
console.log(watch("title")); // watch input value by passing the name of it
return (
<Box
sx={{
width: "414px",
border: "1px solid #000",
p: 2,
borderRadius: 1,
margin: "16px auto",
}}
>
<form onSubmit={handleSubmit(onSubmit)}>
<Typography sx={{ my: "12px" }}>Title:</Typography>
<TextField
placeholder="Ex: Sales Manager"
fullWidth
{...register("title")}
sx={{ mb: 2 }}
></TextField>
<Divider />
<Typography sx={{ my: "12px" }}>Employment type:</Typography>
<InputLabel id="demo-simple-select-label">Employment Type</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={employment}
label="Employment Type"
onChange={handleChange}
{...register("employment")}
sx={{ mb: 2, width: "100%" }}
>
<MenuItem value={"full"}>FullTime</MenuItem>
<MenuItem value={"part"}>PartTime</MenuItem>
</Select>
<Divider />
<Typography sx={{ my: "12px" }}>Company name:</Typography>
<TextField
placeholder="Ex: Microsoft"
fullWidth
{...register("company")}
sx={{ mb: 2 }}
></TextField>
<Divider />
<Typography sx={{ my: "12px" }}>Location:</Typography>
<TextField
placeholder="Ex: London, United Kingdom"
fullWidth
{...register("location")}
sx={{ mb: 2 }}
></TextField>
<Divider />
<Typography sx={{ my: "12px" }}>Date:</Typography>
<TextField
placeholder="Ex: Sales Manager"
fullWidth
{...register("startDate")}
sx={{ mb: 2 }}
></TextField>
<TextField
placeholder="Ex: Sales Manager"
fullWidth
{...register("endDate")}
sx={{ mb: 2 }}
></TextField>
<Divider />
<Typography sx={{ my: "12px" }}>Description:</Typography>
<TextField
fullWidth
{...register("description")}
sx={{ mb: 2 }}
></TextField>
</form>
</Box>
);
}
export default ExprienceCreate;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Unfortunately Anastasia's answer is not correct, because that way you will overwrite react-hook-form's onChange - so this will it prevent from updating it's internal form state and therefore the current value won't be available in your onSubmit callback.
If you need to have an onChange callback for register you can provide a callback in the config options, which you can pass a second argument. Check the docs for more infos.
But i guess the useState for the "employment" field is not needed here as you could just access the current value in your onSubmit callback. If you need to access it before submitting then you could use watch as you did with the "title" field.
Using onChange config option
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
label="Employment Type"
{...register("employment", { onChange: handleChange })}
sx={{ mb: 2, width: "100%" }}
>
Using watch
const employment = watch('employment');
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
label="Employment Type"
{...register("employment")}
sx={{ mb: 2, width: "100%" }}
>
register probably overwrites the onChange you have specified. Try swapping the order of onChange and register.
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={employment}
label="Employment Type"
{...register("employment")}
onChange={handleChange}
sx={{ mb: 2, width: "100%" }}
>
I have a Material UI TextField as an input and I need to force the entered text as uppercase. I have tried using textTransform: "uppercase" as part of the style attribute but this does not seem to work. All of the other styling in my component is applied correctly however the textTransform is not.
I have also tried using the standard style method of passing my style as a prop to the component but I get the same result.
My component:
const MenuInput = (props) => {
const useStyles = makeStyles((theme) => ({
input: {
textTransform: "uppercase",
marginTop: "10px",
width: "100%",
borderRadius: 4,
backgroundColor: "#FFFFFF",
},
}));
const classes = useStyles();
return (
<TextField
className={classes.input}
id={props.id}
color="primary"
label={props.label}
variant="filled"
onChange={(e) => props.onChange(e)}
error={props.isError}
helperText={props.error}
/>
);
};
The output:
You could try applying styles through the inputProps like the following:
<TextField
className={classes.input}
id={props.id}
color="primary"
label={props.label}
variant="filled"
onChange={(e) => props.onChange(e)}
error={props.isError}
helperText={props.error}
inputProps={{ style: { textTransform: "uppercase" } }}
/>
I'll leave a link with a sandbox where I tested that solution.
try adding important
textTransform: "uppercase !important"
Or add inline style
<Textfield style={{textTransform:"uppercase"}} />