Material-ui Autocomplete defaultValue not working - javascript

I tried setting the defaultValue to be "Chairs" and it is not working.
These are the codes:
import React, { useState } from "react";
import TextField from "#mui/material/TextField";
import Autocomplete from "#mui/material/Autocomplete";
import { Items2 } from "./Items2";
export default function ComboBox() {
const [selected, setSelected] = useState("");
console.log(selected);
return (
<>
you selected: {selected}
<br />
<br />
<Autocomplete
disablePortal
isOptionEqualToValue={(option, value) => option?.label === value?.label}
id="combo-box-demo"
options={Items2}
defaultValue="Chairs"
fullwidth
value={selected}
onChange={(event, value) => setSelected(value)}
renderInput={(params) => <TextField {...params} label="Items" />}
/>
</>
);
}
Also in codesandbox: https://codesandbox.io/s/combobox-material-demo-forked-g88fi?file=/demo.js:0-904

You just need to set default value for selected state and remove defaultValue from Autocomplete component:
import React, { useState } from "react";
import TextField from "#mui/material/TextField";
import Autocomplete from "#mui/material/Autocomplete";
import { Items2 } from "./Items2";
export default function ComboBox() {
const [selected, setSelected] = useState("Chairs");
console.log(selected);
return (
<>
you selected: {selected}
<br />
<br />
<Autocomplete
disablePortal
isOptionEqualToValue={(option, value) => option?.label === value?.label}
id="combo-box-demo"
options={Items2}
fullwidth
value={selected}
onChange={(event, value) => setSelected(value)}
renderInput={(params) => <TextField {...params} label="Items" />}
/>
</>
);
}

Related

problem of useState hook while doing it with context

i'm trying to register user on some website and save its data in local storage on every page i need to use context for that, so when i tried to do this without context it all worked and i was saving data in local storage but now i do it with context and it broke and in console.log when i type something in input it shows undefined and useState doesn't work and add items to the object
below code is app.js
import "./App.css";
import * as React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { BrowserRouter } from "react-router-dom";
import Question from "./Question";
import Form from "./Form";
import Language from "./Language";
import Photo from "./Photo";
import Fin from "./Fin";
import CustomizedSteppers from "./Step";
import { createContext, useMemo, useState } from "react";
export const StepperContext = createContext({ step: 0, setStep: () => {} });
export const PagesContext = createContext({ info: {}, setInfo: () => {} });
function App() {
const [info, setInfo] = useState({});
const val = useMemo(() => ({ info, setInfo }), [info]);
const [step, setStep] = useState(0);
const value = useMemo(() => ({ step, setStep }), [step]);
return (
<div className="App">
<StepperContext.Provider value={val}>
<StepperContext.Provider value={value}>
<CustomizedSteppers>
<BrowserRouter>
<Routes>
<Route path="/" index element={<Form />} />
<Route path="Question" index element={<Question />} />
<Route path="Language" index element={<Language />} />
<Route path="Photo" index element={<Photo />} />
<Route path="Finish" index element={<Fin />} />
</Routes>
</BrowserRouter>
</CustomizedSteppers>
</StepperContext.Provider>
</StepperContext.Provider>
</div>
);
}
export default App;
this is the form :
import * as React from "react";
import Box from "#mui/material/Box";
import TextField from "#mui/material/TextField";
import { useState, useContext, createContext,useEffect} from "react";
import MaterialUIPickers from "./Datepicker";
import Stack from "#mui/material/Stack";
import Button from "#mui/material/Button";
import CustomizedSteppers from "./Step";
import { PagesContext, StepperContext } from "./App";
import { useNavigate } from "react-router-dom";
function Form() {
const { step, setStep } = useContext(StepperContext);
const navigate = useNavigate();
const { info, setInfo } = useContext(PagesContext);
console.log(info)
console.log(step)
useEffect(() => {
console.log(info)
}, [info])
const next = () => {
localStorage.setItem("info", JSON.stringify(info));
setStep(1);
navigate("Question");
};
return (
<div className="App">
{/* <CustomizedSteppers /> */}
<Box
component="form"
sx={{
"& > :not(style)": { m: 1, width: "25ch" },
}}
noValidate
autoComplete="off"
/>
<div className="input">
<TextField
color="secondary"
id="outlined-basic"
label="First name"
variant="outlined"
value={info ? info.firstName : ""}
onChange={(e) => {
console.log(info.firstName)
setInfo((prev) => ({ ...prev, firstName: e.target.value }));
}}
/>
<TextField
color="secondary"
id="outlined-basic"
label="Last name"
variant="outlined"
value={info ? info.lastName : ""}
onChange={(e) => {
setInfo((prev) => ({ ...prev, lastName: e.target.value }));
}}
/>
<TextField
id="outlined-number"
type="number"
color="secondary"
placeholder="Phone number"
InputLabelProps={{
shrink: true,
}}
value={info ? info.phoneNumber : ""}
onChange={(e) => {
setInfo((prev) => ({ ...prev, phoneNumber: e.target.value }));
}}
/>
<TextField
id="outlined-basic"
label="City"
color="secondary"
variant="outlined"
type="text"
value={info ? info.city : ""}
onChange={(e) => {
setInfo((prev) => ({ ...prev, city: e.target.value }));
}}
/>
<TextField
id="outlined-basic"
label="Email"
color="secondary"
variant="outlined"
type="email"
value={info ? info.email : ""}
onChange={(e) => {
setInfo((prev) => ({ ...prev, email: e.target.value }));
}}
/>
<MaterialUIPickers></MaterialUIPickers>
</div>
<Button
onClick={next}
style={{ width: "700px" }}
color="secondary"
variant="contained"
>
Next
</Button>
</div>
);
}
export default Form;

How to take TimeInput only in React-Admin?

This code from React-Admin docs allows me to input Date and Time:
import { DateTimeInput } from 'react-admin';
<DateTimeInput source="published_at" />
Is there a way to input ONLY time in React-Admin?
https://mui.com/x/react-date-pickers/time-picker/
import * as React from 'react';
import TextField from '#mui/material/TextField';
import { AdapterDateFns } from '#mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '#mui/x-date-pickers/LocalizationProvider';
import { TimePicker } from '#mui/x-date-pickers/TimePicker';
export default function BasicTimePicker() {
const [value, setValue] = React.useState<Date | null>(null);
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<TimePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
);
}

Getting 'Aw snap! : error code: Out of memory'

I was trying to build simple react-redux app using reducers. But every time I open the website it is popping up this error and I couldn't open the console. I tried to clean cookies and caches but no help.
Whenever I change <Posts /> and <Form /> to simple <h1> tags it works perfectly fine, but I can't find the bug.
My code in
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { reducers } from './reducers/index.js';
import App from './App';
const store = createStore(reducers, compose(applyMiddleware(thunk)));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
);
App.js
import React,{ useEffect, useState } from 'react';
import { Container, AppBar, Typography, Grid, Grow } from '#material-ui/core';
import { useDispatch } from 'react-redux';
import Posts from '../src/components/Posts';
import Form from './components/form';
import { getPosts } from './actions/action';
function App() {
const [currentId, setCurrentId] = useState();
const dispatch = useDispatch();
useEffect(() =>{
dispatch(getPosts());
},[dispatch, currentId]);
return (
<div>
<Container maxWidth='lg'>
<AppBar position='static' color='inherit'>
<Typography variant='h2' align='center' >SimplePRATICE</Typography>
</AppBar>
<Grow in>
<Container>
<Grid container justify='space-between' alignItems='stretch' spacing={3}>
<Grid item xs={12} sm={4}>
<Form currentId={currentId} setCurrentId={setCurrentId} />
</Grid>
</Grid>
</Container>
</Grow>
</Container>
</div>
);
}
export default App;
form.js
import React, { useEffect, useState } from 'react';
import { Paper, Button, TextField, Typography } from '#material-ui/core';
import { useSelector, useDispatch } from 'react-redux';
import { createPost, updatePost } from '../actions/action.js';
function Form({ currentId, setCurrentId }) {
const [postData, setpostData] = useState({ name:'', message:'' });
const post = useSelector((state) => (currentId ? state.posts.find((message) => message._id === currentId ) :null ));
const dispatch = useDispatch();
useEffect(() => {
if (post) setpostData(post);
}, [post]);
const clear = () =>{
setCurrentId(0);
setpostData({ name: '', message:''});
};
const handleSubmit = async (e) => {
e.preventDefault();
if (currentId === 0){
dispatch(createPost(postData));
}else{
dispatch(updatePost(currentId, postData));
}
clear();
};
return (
<Paper>
<Form onSubmit={handleSubmit}>
<Typography>Creating Post</Typography>
<TextField name="name" variant="outlined" label="Name" fullWidth value={postData.name} onChange={(e) => setpostData({ ...postData, name: e.target.value })} />
<TextField name="message" variant="outlined" label="Message" fullWidth multiline rows={4} value={postData.message} onChange={(e) => setpostData({ ...postData, message: e.target.value })} />
<Button varient='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
</Form>
</Paper>
)
}
export default Form
Posts.js
import React from 'react';
import Post from './post.js';
import { Grid } from '#material-ui/core';
import { useSelector } from 'react-redux';
function Posts({ setCurrentId }) {
const posts = useSelector((state) => state.posts);
return (
<Grid container alignItems='stretch' spacing={3}>
{posts.map((post) => (
<Grid key={post._id} item xs={12} sm={6} md={6}>
<Post post={post} setCurrentId={setCurrentId} />
</Grid>
))}
</Grid>
)
}
export default Posts
Post.js
import React from 'react';
import { Card, CardActions, CardContent, Button, Typography } from '#material-ui/core/';
import DeleteIcon from '#material-ui/icons/Delete';
import MoreHorizIcon from '#material-ui/icons/MoreHoriz';
import { useDispatch } from 'react-redux';
import { deletePost } from '../actions/action.js';
function Post({ post, setCurrentId }) {
const dispatch = useDispatch();
return (
<Card>
<div>
<Typography varient='h6'>{post.name}</Typography>
</div>
<di>
<Button style={{ color:'white' }} size='small' onClick={()=> setCurrentId(post._id)}><MoreHorizIcon fontSize='default' /></Button>
</di>
<CardContent>
<Typography vaarient='body2' color='textSecondary' component='p'>{post.message}</Typography>
</CardContent>
<CardActions>
<Button size='small' color='primary' onClick={()=> dispatch(deletePost(post._id))} ><DeleteIcon fontSize='small'>Delete</DeleteIcon></Button>
</CardActions>
</Card>
)
}
export default Post
import axios from 'axios';
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) => axios.patch(`${url}/${id}`, updatedPost);
export const deletePost = (id) => axios.delete(`${url}/${id}`);
Your Form component renders itself:
return (
<Paper>
<Form onSubmit={handleSubmit}>
<Typography>Creating Post</Typography>
<TextField name="name" variant="outlined" label="Name" fullWidth value={postData.name} onChange={(e) => setpostData({ ...postData, name: e.target.value })} />
<TextField name="message" variant="outlined" label="Message" fullWidth multiline rows={4} value={postData.message} onChange={(e) => setpostData({ ...postData, message: e.target.value })} />
<Button varient='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
</Form>
</Paper>
)
I think you meant <form> which is not a react component.
return (
<Paper>
<form onSubmit={handleSubmit}>
<Typography>Creating Post</Typography>
<TextField name="name" variant="outlined" label="Name" fullWidth value={postData.name} onChange={(e) => setpostData({ ...postData, name: e.target.value })} />
<TextField name="message" variant="outlined" label="Message" fullWidth multiline rows={4} value={postData.message} onChange={(e) => setpostData({ ...postData, message: e.target.value })} />
<Button varient='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
</form>
</Paper>
)
You must have selected a wrong element in your html which is not going on well with the code.
Hence please check all the elements properly.
If it is a functional component , check it again.
I had the same issue and it got resolved.

How can i change the both value change and function call in a single onChange

Here is the code, and i want to call apifetcher at the same time when the value of the city changes.how to do that?? is it possible
The value of the city should replace the 'q' value. And after that both the city and the API are passing to an another file.what should I add or remove.
import React, { useState } from "react";
import Cities from "./citylist";
import Autocomplete from "#material-ui/lab/Autocomplete";
import TextField from "#material-ui/core/TextField";
import Content from "./content";
const SearchBar = () => {
const [city, setcity] = useState("");
const [api, setapi] = useState(
`http://api.openweathermap.org/data/2.5/forecast?q=Kurunegala,LK& mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`
);
console.log(city);
Content(city, api);
const apiFtecher = () => {
return setapi(
`http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`
);
};
return (
<div style={{ width: 300 }}>
<Autocomplete
freeSolo
id="free-solo-2-demo"
disableClearable
options={Cities.map((option) => option.name)}
renderInput={(params) => (
<TextField
{...params}
label="city"
margin="normal"
variant="outlined"
InputProps={{ ...params.InputProps, type: "search" }}
onChange={(e) => setcity(e.target.value)}
onBlur={(e) => setcity(e.target.value)}
/>
)}
/>
</div>
);
};
export default SearchBar;
There doesn't seem to be a need for the city state variable.
To call apiFtecher[sic] on every change of the input, you would do something like this:
const apiFtecher = e => {
const city = e.target.value;
return (
setapi(`http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`)
);
}
And update the element to:
<TextField
{...params}
label="city"
margin="normal"
variant="outlined"
InputProps={{ ...params.InputProps, type: 'search' }}
onChange={apiFtecher}
/>

Delete tag in uncontrolled "ChipInput" using react hook form

I'm using react-hook-form to handle form values, Its working fine for all other input types like TextFeild, Select from material but facing issues with "material-ui-chip-input" as adding tag working fine but not able to delete tag on click of cross button or hitting backspace. I'm struggling on this from a long. Anyone please help in it.
import React from "react";
import FormControl from "#material-ui/core/FormControl";
import { Controller } from "react-hook-form";
import ChipInput from "material-ui-chip-input";
const ReactHookFormChips = ({
name,
label,
control,
defaultValue,
children,
rules,
error,
chipsError,
...props
}) => {
const labelId = `${name}-label`;
return (
<FormControl {...props}>
<Controller
as={
<ChipInput
label={label}
helperText={chipsError}
error={error}
/>
}
name={name}
control={control}
defaultValue={defaultValue}
rules={rules}
/>
</FormControl>
);
};
export default ReactHookFormChips;
calling this component like
<ReactHookFormChips
id="levelLabel"
name="tags"
label="Select Tags"
control={control}
defaultValue={[]}
margin="normal"
error={!!errors?.tags}
rules={{ required: true }}
chipsError={errors?.tags && "Tag is required."}
/>
I fixed it using render prop.
import React from "react";
import FormControl from "#material-ui/core/FormControl";
import InputLabel from "#material-ui/core/InputLabel";
import { Controller } from "react-hook-form";
import ChipInput from "material-ui-chip-input";
const ReactHookFormChips = ({
name,
label,
control,
defaultValue,
children,
rules,
error,
chipsError,
...props
}) => {
const labelId = `${name}-label`;
return (
<FormControl {...props}>
<Controller
render={({ onChange, onBlur, value }) =>
<ChipInput
onChange={onChange}
label={label}
helperText={chipsError}
error={error}
/>
}
name={name}
control={control}
defaultValue={defaultValue}
rules={rules}
/>
</FormControl>
);
};
export default ReactHookFormChips;

Categories