Customizing the default value in the Date Textfield | React Material - reactjs

I am new to Material UI. So, here i am using a Textfield type Date. By defaut in the textfield it shows "dd-mm-yyyy". But, i want to show an string value by default, like this "Add DOB (MM/DD/YYYY)". I tried some ways, its not taking the string value. Please let me know, how can i achieve this.
import React from 'react';
import { render } from 'react-dom';
import TextField from 'material-ui/TextField';
const App = () => (
<div style={styles}>
<TextField
id="date"
label="Add Date of Birth"
type="date"
name="DateOfBirth"
defaultValue="Add DOB"
className="form-field"
InputLabelProps={{
shrink: true,
}}
/>
</div>
);
render(<App />, document.getElementById('root'));

I'm not sure what default you are asking. I am assuming two things here: default value for the date or some kind of text accompanying the date.
If you want to set default value for the TextField it is best to set the value prop for the component with a state as in value={stateValue}. If you want to add some text to accompany the date you can try Input Adornments in the Material UI.
Code example for this:
import React from "react";
import InputAdornment from "#material-ui/core/InputAdornment";
import { makeStyles } from "#material-ui/core/styles";
import TextField from "#material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
container: {
display: "flex",
flexDirection: "column",
flexWrap: "wrap"
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 200
},
adornment: {
width: 110
},
dense: {
marginTop: 19
},
menu: {
width: 200
}
}));
export default function TextFields() {
const classes = useStyles();
const [values, setValues] = React.useState({
date: "1993-11-01"
});
const handleChange = name => event => {
console.log(event.target.value);
setValues({ ...values, [name]: event.target.value });
};
return (
<form className={classes.container} noValidate autoComplete="off">
<TextField
id="date"
label="Add Date of Birth"
type="date"
name="DateOfBirth"
// defaultValue="Add DOB"
InputProps={{
startAdornment: (
<InputAdornment className={classes.adornment} position="start">
Add DOB
</InputAdornment>
)
}}
value={values.date}
className={classes.textField}
onChange={handleChange("date")}
InputLabelProps={{
shrink: true
}}
/>
<TextField
id="standard-name"
label="Date Text"
className={classes.textField}
value={values.date}
onChange={handleChange("date")}
margin="normal"
/>
</form>
);
}
Demo Codesandbox: TextField - date

Related

Price range with slider and textfield MUI

I'm trying to create a price range using mui slider, and 2 text fields for the min and max prices.
I'm getting the numbers correctly in console, the problem is, the slider is not moving in the ui!!
Here's the code on codesandbox:
https://codesandbox.io/s/jolly-stonebraker-er88ri?file=/src/App.js
Here you are trying to change the Max and Min value of the slider which needs to stay as it is. We have to change the value of the slider, in order to move it, not its Min and Max values.
import React, { useState, useEffect } from "react";
import { Stack, Typography, Slider, TextField } from "#mui/material";
export default function App() {
const [minNum, setMinNum] = useState(0);
const [maxNum, setMaxNum] = useState(1000);
const minmin = 0;
const maxmax = 1000;
const [priceRangeValue, setPriceRangeValue] = useState([0, 1000]);
const handlePriceRangeChange = (event, newValue) => {
setMinNum(newValue[0]);
setMaxNum(newValue[1]);
setPriceRangeValue(newValue);
};
console.log(priceRangeValue);
return (
<>
<Slider
getAriaLabel={() => "Price range"}
value={priceRangeValue}
onChange={handlePriceRangeChange}
valueLabelDisplay="auto"
min={minmin}
max={maxmax}
/>
<Stack direction="row" justifyContent="space-evenly" alignItems="center">
<TextField
label="min"
type="number"
variant="outlined"
InputLabelProps={{ shrink: true }}
sx={{ width: "90px" }}
value={minNum}
onChange={(e) => {
setMinNum(Number(e.target.value));
setPriceRangeValue([Number(e.target.value), priceRangeValue[1]]);
}}
/>
<Typography>-</Typography>
<TextField
label="max"
type="number"
variant="outlined"
InputLabelProps={{ shrink: true }}
sx={{ width: "90px" }}
value={maxNum}
onChange={(e) => {
setMaxNum(Number(e.target.value));
setPriceRangeValue([priceRangeValue[0], Number(e.target.value)]);
}}
/>
</Stack>
</>
);
}
Since minNum and maxNum corresponds to priceRangeValue[0] and priceRangeValue[1] respectively.
Therefor we can directly use priceRangeValue and remove the useStates.
import React, { useState, useEffect } from "react";
import { Stack, Typography, Slider, TextField } from "#mui/material";
export default function App() {
const minmin = 0;
const maxmax = 1000;
const [priceRangeValue, setPriceRangeValue] = useState([0, 1000]);
const handlePriceRangeChange = (event, newValue) => {
setPriceRangeValue(newValue);
};
console.log(priceRangeValue);
return (
<>
<Slider
getAriaLabel={() => "Price range"}
value={priceRangeValue}
onChange={handlePriceRangeChange}
valueLabelDisplay="auto"
min={minmin}
max={maxmax}
/>
<Stack direction="row" justifyContent="space-evenly" alignItems="center">
<TextField
label="min"
type="number"
variant="outlined"
InputLabelProps={{ shrink: true }}
sx={{ width: "90px" }}
value={priceRangeValue[0]}
onChange={(e) => {
setPriceRangeValue([Number(e.target.value), priceRangeValue[1]]);
}}
/>
<Typography>-</Typography>
<TextField
label="max"
type="number"
variant="outlined"
InputLabelProps={{ shrink: true }}
sx={{ width: "90px" }}
value={priceRangeValue[1]}
onChange={(e) => {
setPriceRangeValue([priceRangeValue[0], Number(e.target.value)]);
}}
/>
</Stack>
</>
);
}
The min and max properties of the Slider component just mean the minimum and maximum values of that slider, not the minimum and maximum of the range. So you need to remove the following 2 lines in the definition of handlePriceRangeChange function:
setMinNum(newValue[0]);
setMaxNum(newValue[1]);
So, the handlePriceRangeChange function should be as follows:
const handlePriceRangeChange = (event, newValue) => {
setPriceRangeValue(newValue);
};

React Form returning null values with useRef() hook

I want to get input data from the user when they click submit form button. When clicked, i'm getting a response object with null values shown in the screenshot. From what I understand, I don't want useState because it'll make the page do a re-render, and I don't want that. This is my first time with useRef, is there something i'm missing?
import Box from "#mui/material/Box";
import Grid from "#mui/material/Grid";
import Typography from "#mui/material/Typography";
import TextField from "#mui/material/TextField";
import Button from "#mui/material/Button";
import { useRef } from "react";
const ContactSection = () => {
let nameRef = useRef(null); // name
let emailRef = useRef(null); // email
let messageRef = useRef(null); // message
const formSubmit = (event) => {
event.preventDefault();
const data = {
name: nameRef.current.value,
email: emailRef.current.value,
message: messageRef.current.value,
};
console.log(data);
};
return (
<Box component="form">
<TextField
ref={nameRef}
type="text"
id="form-name"
label="Name"
sx={{ mt: 2 }}
></TextField>
<TextField
ref={emailRef}
type="email"
id="form-email"
label="Email"
sx={{ mt: 2 }}
></TextField>
<TextField
ref={messageRef}
type="text"
id="form-msg"
label="Message"
multiline
rows={5}
sx={{ mt: 2 }}
></TextField>
</Box>
<Button
variant="contained"
onClick={formSubmit}
sx={{
mt: 4,
"&:hover": {
color: "secondary.main",
transition: "ease-in 0.2s",
transform: "scale(1.05)",
},
}}
>
Submit
</Button>
);
};
export default ContactSection;
I'm getting this error in the console when trigger formSubmit handle
When using MUI TextField change the ref to inputRef
<Box component="form">
<TextField
inputRef={nameRef}
type="text"
id="form-name"
label="Name"
sx={{ mt: 2 }}
></TextField>
<TextField
inputRef={emailRef}
type="email"
id="form-email"
label="Email"
sx={{ mt: 2 }}
></TextField>
<TextField
inputRef={messageRef}
type="text"
id="form-msg"
label="Message"
multiline
rows={5}
sx={{ mt: 2 }}
></TextField>
</Box>
This will give the correct output in the console log
You have to use inputRef instead of ref for more information refer to the official doc. https://mui.com/api/text-field/
Use inputRef instead of ref for material UI text field component .
Reference : https://mui.com/components/text-fields/#main-content

Material-UI: How to add Icons in the TextField label?

I am trying to add Material-UI icons into TextField component, I want to add it to the label not in input Field.
Eg:
through Inputprops we can pass and add icon to input, but I want it in label. How to achieve this..?
<Field label="Name" required /> -> Name*
What I want to achieve is:
<Field label="Name" required /> -> Name*(icon)
It can be achieved by using flex and order properties of CSS, lightweight and effective.
Result:
Full code sample :
Code fragment :
const useStyles = makeStyles({
root: {
"& .MuiFormLabel-root": {
display: "flex",
alignItems: "center",
"& .myIcon": {
paddingLeft: "8px",
order: 999
}
}
}
});
const Demo = () => {
const classes = useStyles();
return (
<TextField
className={classes.root}
required
label={
<Fragment>
I am label
<SettingsRounded className="myIcon" fontSize="small" />
</Fragment>
}
variant="outlined"
/>
);
};
Hope to help you !
Because label can accept a ReactNode, you add an icon component to the TextField like this:
import { makeStyles } from "#material-ui/core/styles";
import TextField from "#material-ui/core/TextField";
import Add from "#material-ui/icons/Add";
const useStyles = makeStyles({
root: {
"& label": {
marginTop: -3, // fix the icon alignment issue
}
},
label: {
display: "inline-flex",
alignItems: "center"
}
});
export default function BasicTextFields() {
const classes = useStyles();
return (
<TextField
className={classes.root}
label={
<div className={classes.label}>
<span>My Label</span>
<Add />
</div>
}
variant="outlined"
/>
);
}
Live Demo

React-Redux connecting dispatching a function component

I am going through trouble to connectand dispatch in function based component. I know how to connect and dispatch class based component.
This is my code;
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import TextField from '#material-ui/core/TextField';
import Paper from '#material-ui/core/Paper';
import Grid from '#material-ui/core/Grid';
import Button from '#material-ui/core/Button';
import SaveIcon from '#material-ui/icons/Save';
import { connect } from "react-redux";
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 200,
},
dense: {
marginTop: 19,
},
menu: {
width: 200,
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
button: {
margin: theme.spacing(1),
},
}));
export default function TextFields() {
const classes = useStyles();
const [values, setValues] = React.useState({
ssn: '',
phone: '',
email: '',
multiline: 'Controlled',
});
const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value });
};
const onSubmit = () => {
const data = {
ssn: values.ssn,
phone: values.phone,
email: values.email
}
console.log(data)
this.props.dispatch({type: 'SUBMIT', data})
}
return (
<React.Fragment>
<Grid item xs={12}>
<Paper className={classes.paper}>xs=12</Paper>
</Grid>
<form className={classes.container} noValidate autoComplete="off">
<TextField
id=""
label="SSN"
value={values.ssn}
onChange={handleChange('ssn')}
type="number"
className={classes.textField}
name='ssn'
margin="normal"
/>
<TextField
id=""
label="Phone"
value={values.phone}
onChange={handleChange('phone')}
type="number"
className={classes.textField}
name='phone'
margin="normal"
/>
<TextField
id=""
label="Email"
value={values.email}
onChange={handleChange('email')}
type="email"
className={classes.textField}
margin="normal"
name='email'
/>
<Button
onClick={() => onSubmit()}
variant="contained"
color="primary"
size="small"
className={classes.button}
startIcon={<SaveIcon />}
>
Save
</Button>
</form>
</React.Fragment>
);
}
Can anyone help me to dispatch the data or connect ? THANKS IN ADVANCE

How I can save the value for date from Date pickers?

I want save value for date from this code, I use vscode and reactjs and Material package.
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '#material-ui/core/styles';
import TextField from '#material-ui/core/TextField';
const styles = theme => ({
container: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit,
width: 200,
},
});
function DatePickers(props) {
const { classes } = props;
//console.log(props)
return (
<form className={classes.container} noValidate>
<TextField
id="date"
label="Birthday"
type="date"
defaultValue="2017-05-24"
className={classes.textField}
InputLabelProps={{
shrink: true,
}}
/>
</form>
);
}
DatePickers.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(DatePickers);
In order to save the selected date, your code should look something like this,
import React, { Component } from "react";
import PropTypes from "prop-types";
import { withStyles } from "#material-ui/core/styles";
import TextField from "#material-ui/core/TextField";
const styles = theme => ({
container: {
display: "flex",
flexWrap: "wrap"
},
textField: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit,
width: 200
}
});
class DatePickers extends Component {
state = {
date: "2017-05-24"
};
handleChange = event => {
this.setState({ date: event.target.value });
};
render() {
const { classes } = this.props;
console.log(this.state);
return (
<form className={classes.container} noValidate>
<TextField
id="date"
label="Birthday"
type="date"
value={this.state.date}
onChange={this.handleChange}
className={classes.textField}
InputLabelProps={{
shrink: true
}}
/>
</form>
);
}
}
DatePickers.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(DatePickers);

Resources