Mui DatePicker change date format - html

I am trying to customise the mui DatePicker. I want the date format to be as follows: Day, DD Month.
example: Monday, 10 September
here is my code:
<LocalizationProvider dateAdapter={AdapterDateFns} locale={frLocale}>
<Stack spacing={3}>
<ThemeProvider theme={calendarTheme}>
<DatePicker
disabled={false}
//the current format
inputFormat="MM/dd/yyyy"
leftArrowButtonText={t("notification.previous_month")}
rightArrowButtonText={t("notification.next_month")}
minDate={today}
InputProps={{
classes: {
notchedOutline: classes.noBorder,
root: classes.reverse,
},
}}
components={{
OpenPickerIcon: Table,
SwitchViewIcon: ArrowDown,
}}
value={value}
onChange={handlechange}
renderInput={(params: any) => (
<TextField
style={{
color: "red",
}}
{...params}
/>
)}
/>
</ThemeProvider>
</Stack>
</LocalizationProvider>

You need to use fromat like format="EEEE, MM MMMM":
<DesktopDatePicker
label="Date desktop"
inputFormat="EEEE, MM MMMM"
openTo={"day"}
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>

Related

How to Implement a search function in reactJS using MaterialUI

I try to develop a pokedex using the pokeapi. For now it works fine, the pokemon are fetched correctly and are displayed in a container. Now i want to implement a function to search and filter the pokemon. Therefore i used MaterialUI to put a searchBar on top of the App.
The fetched pokemon are given from App.js to my Component PokemonList which maps the data. My idea is now to filter the pokemonData before it is given to PokemonList to map only the pokemon i am looking for. But here i am stuck. I have no idea how to connect the search function with my pokemonData Hook from App.js . Can you help me?
This is my searchBar Component:
const SearchAppBar = () => {
const [search, setSearch] = useState("");
console.log(search)
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="static" sx={{ bgcolor: "black"}}>
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="open drawer"
sx={{ mr: 2 }}
>
<MenuIcon />
</IconButton>
<Typography
variant="h6"
noWrap
component="div"
sx={{ flexGrow: 1, display: { xs: 'none', sm: 'block' } }}
>
<img src={logo} alt="logo" width="150" height="auto" />
</Typography>
<Search>
<SearchIconWrapper>
<SearchIcon />
</SearchIconWrapper>
<StyledInputBase
onChange={(e) => setSearch(e.target.value)}
id = 'searchbox'
placeholder="Search for Pokémon..."
inputProps={{'aria-label': 'search'}}
/>
</Search>
</Toolbar>
</AppBar>
</Box>
);
}
export default SearchAppBar;
you should save the entered value from input into a state and filter your data based on that state

How to get Formik error messages to align with input box?

How do I get these messages to align with the input boxes? I'm not sure how I could style this?
The Formik exists outside of the ReactJS return so I can't put it in a and style. And what is the reason that the error message is aligning to the edge of the box anyways? I'm new to React and Formik is what was recommended in the Chakra UI Docs to use for form handling.
Here is my code:
import React from 'react';
import { Text, Box } from '#chakra-ui/react'
import { Input } from "#chakra-ui/input"
import { Button } from "#chakra-ui/button";
import { FormControl, FormLabel, FormErrorMessage } from "#chakra-ui/form-control";
import { Heading, VStack } from "#chakra-ui/layout";
import { useFormik } from "formik";
import * as Yup from "yup";
import "../Signup.css";
import SignupLogo from '../assets/Shots.jpg';
const Signup = () => {
// Formik Hook to validate password and username length
const formik = useFormik({
initialValues: {
username: "",
email: "",
password: ""
},
validationSchema: Yup.object({
username: Yup.string().required("Username Required").min(6, "Username much be minimum of 6 characters long, username too short! "),
password: Yup.string().required("Password Required").min(8, "Password much be minimum of 5 characters long, password too short! "),
}),
onSubmit: (values, actions) => {
alert(JSON.stringify(values, null, 3));
actions.resetForm();
}
});
return (
<body className='SignupImg'>
<VStack
as="form"
mx="auto"
w={{ base: "75%", md: 500 }}
h="100vh"
justifyContent="center"
onSubmit={formik.handleSubmit}
className='winterCitrus'>
<Heading color="#421413">
Sign Up!
</Heading>
{/* Form for Username */}
<FormControl py={3} id="user_id" isInvalid={formik.errors.username && formik.touched.username}>
<FormLabel colorScheme="black">
<Text color="#932D30" textAlign="center">
Username
</Text>
</FormLabel>
<Input
bg="white"
textColor="black"
name='username'
placeholder="enter username"
{...formik.getFieldProps("username")}
width={"300px"}
/>
<FormErrorMessage>{formik.errors.username}</FormErrorMessage>
</FormControl>
{/* Form for Email */}
<FormControl py={3} id="email_id">
<FormLabel>
<Text color="#932D30" textAlign="center">
Email
</Text>
</FormLabel>
<Input
bg="white"
textColor="black"
name='email'
placeholder='enter email'
onChange={formik.handleChange}
value={formik.values.email}
width={"300px"}
/>
</FormControl>
{/* Form for Password */}
<FormControl py={3} id="password_id" isInvalid={formik.errors.password && formik.touched.password}>
<FormLabel>
<Text color="#932D30" textAlign="center">
Password
</Text>
</FormLabel>
<Input
bg="white"
textColor="black"
name='password'
placeholder='enter password'
{...formik.getFieldProps("password")}
width={"300px"}
/>
<FormErrorMessage>{formik.errors.password}</FormErrorMessage>
</FormControl>
<Button type='submit' variant="outline" bgColor="#421413">
Create Account
</Button>
</VStack>
</body>
)
};
export default Signup;
You could try to use something like this in your code for example
{formik.touched.username && formik.errors.username && (
<span className='error'>{formik.errors.username}</span>
)}
You could try MUI. they have dedicated docs for formik and yup

Access Object Properties in React

In my react app, I have an array of objects in a file(users.js) and I have another file(contacts.jsx). I am putting the material ui card in contacts.jsx file and in that card I want to access properties of object.
I have tried to access it by using dot(.) operator but I am getting undefined in console.log. What mistake am I doing and How can I access properties like avatar, email, first_name etc.?
users.js
const users = [{
id: 1,
email: "george.bluth#reqres.in",
first_name: "George",
last_name: "Bluth",
avatar: "https://reqres.in/img/faces/1-image.jpg"
},
{
id: 2,
email: "janet.weaver#reqres.in",
first_name: "Janet",
last_name: "Weaver",
avatar: "https://reqres.in/img/faces/2-image.jpg"
}]
export default users;
contacts.jsx
import React from "react";
import FilterListIcon from '#mui/icons-material/FilterList';
import { Button, Card, CardActions, CardContent, CardMedia, Typography } from "#mui/material";
import users from "../constants/users";
const Contacts = () => {
return (
<div className="parentDiv">
{
console.log(users.email,'email') // Result: undefined 'email'
}
<div className="header">
<h1>Robo Space</h1>
<input className="searchFilter" type='text' placeholder="Search here" />
<span className="filterIcon"><FilterListIcon /></span>
</div>
<div className="body">
<Card sx={{ maxWidth: 345 }}>
<CardMedia
component="img"
height="140"
img={users.avatar}
alt="robo img"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{users.first_name}
</Typography>
<Typography variant="body2" color="text.secondary">
{users.last_name}
</Typography>
</CardContent>
<CardActions>
<Button size="small">Show More</Button>
</CardActions>
</Card>
</div>
</div>
)
}
export default Contacts;
To access single properties you can use the dot operator like users[0].email, to access the properties dynamically you can use .map() like that:
import React from "react";
import FilterListIcon from '#mui/icons-material/FilterList';
import { Button, Card, CardActions, CardContent, CardMedia, Typography } from "#mui/material";
import users from "./users";
const Contacts = () => {
return (
<div className="parentDiv">
{
console.log(users[0].email,'email') // Result: undefined 'email'
}
<div className="header">
<h1>Robo Space</h1>
<input className="searchFilter" type='text' placeholder="Search here" />
<span className="filterIcon"><FilterListIcon /></span>
</div>
<div className="body">
{users.map((user)=>{
return (
<Card sx={{ maxWidth: 345 }}>
<CardMedia
component="img"
height="140"
src={user.avatar}
alt="robo img"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{user.first_name}
</Typography>
<Typography variant="body2" color="text.secondary">
{user.last_name}
</Typography>
</CardContent>
<CardActions>
<Button size="small">Show More</Button>
</CardActions>
</Card>
)
})}
</div>
</div>
)
}
export default Contacts;
Here is a Sandbox in case you need it.

TypeError: (intermediate value).toDate is not a function

I'm trying to display a timestamp value from my firestore collection but i'm getting this error "TypeError: (intermediate value).toDate is not a function" where i marked with the ">>" below.
I made it a timestamp before submitting it into firestore but now to display it i need it as a Date value
Do you have any solutions?
componentDidMount() {
db.collection("mycollection")
.get()
.then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data());
this.setState({ costumers: data });
});
}
render(){
const { costumers } = this.state;
return (
<Card
>
<PerfectScrollbar>
<Box minWidth={1050}>
<Table >
<TableHead>
<TableRow>
<TableCell padding="checkbox">
</TableCell>
{costumers.map(costumer => (
<TableBody>
<TableRow
>
<TableCell padding="checkbox">
<Checkbox
value="true"
/>
</TableCell>
<TableCell>
<Box
alignItems="center"
display="flex"
>
<Typography
color="textPrimary"
variant="body1"
>
{costumer.name}
</Typography>
</Box>
</TableCell>
<TableCell>
{costumer.surname}
</TableCell>
<TableCell>
{costumer.email}
</TableCell>
<TableCell>
{costumer.phone}
</TableCell>
<TableCell>
>> {new Date(costumer.date).toDate()}
</TableCell>
<TableCell>
{costumer.time}
</TableCell>
<TableCell>
{costumer.service}
</TableCell>
</TableRow>
</TableBody>
))}
</Table>
You can easily get the timestamp from Firebase Server itself by using the following code.
import firebase from 'firebase';
var TimeStamp = firebase.firestore.FieldValue.serverTimestamp();
The serverTimestamp() function will return the timestamp from the firebase server itself. Here, the value of TimeStampwill be in this format :
<Full name of the month> dd, yyyy hh:mm:ss <Time zone of your location>
If you want to display date, you can simply display it as a string. You can't display a date value inside a <TableCell>. You have to convert it to a string.
EDIT
When you receive a timestamp value it will already be in date format. You have to use toDateString() to convert it to a string.
First, you have to multiply the timestamp value by 1000 and then wrap the timestamp value in the new date function like this:
new Date(post.timestamp?.seconds * 1000)
Then you have to call the toDateString function on the date object:
new Date(post.timestamp?.seconds * 1000).toDateString()

Difference in Months between two dates in React.js using KeyboardDatePicker

const Index = (props) => {
const [selectedDate, setSelectedDate] = useState(
new Date("2014-08-18T21:11:54")
);
const handleDateChange = (date) => {
setSelectedDate(date);
};
return (
<div>
//first date picker
<MuiPickersUtilsProvider
utils={DateFnsUtils}
// className={classes.formControlNew}
style={{ width: "100%" }}
>
<KeyboardDatePicker
style={{ marginLeft: "5%", width: "91%" }}
margin="normal"
id="date-picker-dialog1"
label="Start Date"
format="MM/dd/yyyy"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
// second date picker
<MuiPickersUtilsProvider
utils={DateFnsUtils}
style={{ width: "100%" }}
>
<KeyboardDatePicker
style={{ marginLeft: "5%", width: "91%" }}
margin="normal"
id="date-picker-dialog2"
label="End Date"
format="MM/dd/yyyy"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
</MuiPickersUtilsProvider>
</div>
);
};
There are two date pickers using which I am taking two dates from user .In which first date is start date & second is End Date . I want to calculate difference between these two dates in months.How should i get the difference in months ? What are the calculations need to be done in Reactjs .
There are a few things missing here.
You are going to want to duplicate selectedDate and handleDateChange so that you can keep track of the two dates separately. Perhaps selectedStartDate and selectedEndDate
To calculate the difference, I would recommend using the moment npm package with syntax similar to:
const months = moment.duration(moment(selectedEndDate).diff(moment(selectedStartDate))).asMinutes()