How to use useRef with Material UI - javascript

There is something wrong with the code but I didn't found what is it exactly, I guess the question is how to use useRef with Material UI?
I'm trying to code a login page, the code worked fine with original but when I used Material UI's it stopped.
The Code:
import { useContext, useRef } from "react";
import { Context } from "../../context/Context";
import axios from "axios";
import { useState } from "react"
import TextField from '#mui/material/TextField';
import Box from '#mui/material/Box';
import EmailIcon from '#mui/icons-material/Email';
import LockIcon from '#mui/icons-material/Lock';
export default function Login() {
const userRef = useRef();
const passwordRef = useRef();
const { dispatch, isFetching } = useContext(Context);
const [error, setError] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/auth/login", {
username: userRef.current.value,
password: passwordRef.current.value,
});
dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
} catch (err) {
dispatch({ type: "LOGIN_FAILURE" });
setError(true)
}
};
return (
<div className="login">
<form className="loginForm" onSubmit={handleSubmit}>
<Box>
<div>
<TextField
type="email"
required
id="outlined-basic"
label="Email"
variant="outlined"
ref={userRef}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<EmailIcon />
</InputAdornment>
),
}}
/>
<TextField
id="outlined-basic"
label="Password"
variant="outlined"
ref={passwordRef}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<LockIcon />
</InputAdornment>
),
}}
/>
</div>
</Box>
</form>
</div>
)
}
I don't know if using ref is correct in Material UI!

The better way to work with MUI TextField is to use a state like this instead of a ref:
const [userEmail, setUserEmail] = useState("")
return <TextField ... value={userEmail} onChange={(e)=>{setUserEmail(e.target.value)}} />
However if you still want to use a useRef instead, maybe the prop inputRef is what you're seeking

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 set initial state with most up to date data returned from API?

I'm making a simple form to edit an app, the initial state of the name & description of the app is set using the data returned from the API.
Currently, when submitting the form the initial data seems to be logging as undefined, the name & description is being set as undefined which occurs in the first render (I have commented in the code where the logs are)
How can I make sure the initial state of name & description has the most up to date information?
Is the excessive renders the problem?
Thanks for taking a look, any help would be appreciated.
import React, { useState, useContext, useEffect } from "react";
import Typography from "#material-ui/core/Typography";
import Button from "#material-ui/core/Button";
import Container from "#material-ui/core/Container";
import SaveIcon from "#mui/icons-material/Save";
import CloseIcon from "#mui/icons-material/Close";
import { makeStyles } from "#material-ui/styles";
import TextField from "#material-ui/core/TextField";
import { Grid } from "#mui/material";
import { useDispatch } from "react-redux";
import { updateApp, updateSelectedApp } from "../../services/reducers/apps";
import { EndpointContext } from "../../baxios/EndpointProvider";
import { useParams } from "react-router-dom";
export default function EditApp() {
const { appid } = useParams();
const classes = useStyles();
const dispatch = useDispatch();
const endpoints = useContext(EndpointContext);
const [selectedApp, setSelectedApp] = useState({});
const [isLoaded, setIsLoaded] = useState(false); // <--- Is there anyway I can also remove this useState? without this the default values in the forms dont populate
useEffect(() => {
async function fetchApp() {
await endpoints.appEndpoints.get(appid).then((response) => {
if (response.status === 200) {
setSelectedApp(response.data);
setIsLoaded(true);
}
});
}
fetchApp();
}, []);
useEffect(() => {
console.log(selectedApp);
}, [selectedApp]);
const [name, setName] = useState(selectedApp.name);
const [description, setDescription] = useState(selectedApp.description);
console.log("---", name, selectedApp.name); // <--- The page renders 3 times, each render log looks like this
// 1st render - --- undefined, undefined
// 2nd render - --- undefined, Appname
// 3rd render - --- undefined, Appname
const handleSubmit = (e) => {
e.preventDefault();
console.log("triggered", name, description); // <--- This logs (triggered, undefined, undefined)
if (name && description) {
const body = { name: name, description: description };
endpoints.appEndpoints.put(selectedApp.id, body).then((response) => {
if (response.status === 200) {
dispatch(updateApp(response.data));
setSelectedApp(response.data);
setName(selectedApp.name);
setDescription(selectedApp.description);
}
});
}
};
return (
<div style={{ margin: 100, marginLeft: 350 }}>
{isLoaded ? (
<Container size="sm" style={{ marginTop: 40 }}>
<Typography
variant="h6"
color="textSecondary"
component="h2"
gutterBottom
>
Edit App
</Typography>
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField
className={classes.field}
onChange={(e) => setName(e.target.value)}
label="App Name"
variant="outlined"
color="secondary"
fullWidth
required
size="small"
defaultValue={selectedApp.name}
error={nameError}
/>
<TextField
className={classes.field}
onChange={(e) => setDescription(e.target.value)}
label="Description"
variant="outlined"
color="secondary"
rows={4}
fullWidth
required
size="small"
defaultValue={selectedApp.description}
error={descriptionError}
/>
<Grid container spacing={2}>
<Grid item>
<Button
// onClick={handleSubmit}
type="submit"
color="primary"
variant="contained"
endIcon={<SaveIcon />}
>
Save
</Button>
</Grid>
</Grid>
</form>
</Container>
) : (
<></>
)}
</div>
);
}
When using const [name, setName] = useState(defaultName), if the defaultName is updated in a future render, then the name value will not be updated to the this latest value.
So in your case you can make the following changes :
const [name, setName] = useState();
const [description, setDescription] = useState();
useEffect(() => {
setName(selectedApp.name)
setDescription(selectedApp.description)
}, [selectedApp])
)
Name and Description are undefined
Your selectedApp is initialized as an empty object. Your useEffect fires a request off to retrieve that data, but the page renders once before it gets the response. There are a couple of ways to handle this. You could do anything from displaying a loading icon on the field, to having a default value for the field until your useEffect with [selectedApp] is called. Once that information is retrieved and sent back, your information will be up to date in state, but if you need to store it for later, you'll need to build out a function to save that data.
Default value:
const [name, setName] = useState(selectedApp.name ?? "Your default value here");
const [description, setDescription] = useState(selectedApp.description ?? "Your default value here");
Loading icon:
{selectedApp ? (
<form noValidate autoComplete="off" onSubmit={handleSubmit}>
<TextField
className={classes.field}
onChange={(e) => setName(e.target.value)}
label="App Name"
variant="outlined"
color="secondary"
fullWidth
required
size="small"
defaultValue={selectedApp.name}
error={nameError}
/>
<TextField
className={classes.field}
onChange={(e) => setDescription(e.target.value)}
label="Description"
variant="outlined"
color="secondary"
rows={4}
fullWidth
required
size="small"
defaultValue={selectedApp.description}
error={descriptionError}
/>
<Grid container spacing={2}>
<Grid item>
<Button
// onClick={handleSubmit}
type="submit"
color="primary"
variant="contained"
endIcon={<SaveIcon />}
>
Save
</Button>
</Grid>
</Grid>
</form>
) : <LoadingIconComponent/>}

Page is not showing while using a component for styling

I am trying to use a container to simplify some styling while learning React and I am having some issues.
Currently this is my Component
import React from 'react'
import { Container, Row, Col } from 'react-bootstrap'
const FormContainer = ({ childern }) => {
return (
<Container>
<Row className="justify-content-md-center">
<Col xs={12} md={6}>
{childern}
</Col>
</Row>
</Container>
)
}
export default FormContainer
And this is where I am loading it into
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Form, Button, Row, Col } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import Message from '../components/Message'
import Loader from '../components/Loader'
import FormContainer from '../components/FormContainer'
import { login } from '../actions/userActions'
const LoginScreen = ({location, history}) => {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const dispatch = useDispatch()
const userLogin = useSelector(state => state.userLogin)
const {loading, error, userInfo} = userLogin
const redirect = location.search ? location.search.split('=')[1] : '/' // Takes location of Url, splits after the equals sign, and everything right of it or takes us back to '/'
useEffect(()=> {
if(userInfo) {
history.push(redirect)
}
}, [history, userInfo, redirect])
const submitHandler = (e) => {
e.preventDefault()
dispatch(login(email, password))
}
return (
<FormContainer>
<h1>Sign In</h1>
{error && <Message variant='danger'>{error}</Message>}
{loading && <Loader/>}
<Form onSubmit={submitHandler}>
<Form.Group controlId='email'>
<Form.Label>Email Address</Form.Label>
<Form.Control type='email' placeholder="Enter email" value={email} onChange={(e) => setEmail(e.target.value)}>
</Form.Control>
</Form.Group>
<Form.Group controlId='password'>
<Form.Label>Password</Form.Label>
<Form.Control type='password' placeholder="Enter password" value={password} onChange={(e) => setPassword(e.target.value)}>
</Form.Control>
</Form.Group>
<Button type='submit' variant='primary'>
Sign In
</Button>
</Form>
<Row className='py-3'>
<Col>
New Customer <Link to={redirect ? `/register?redirect=${redirect}` : '/register'}>
Register
</Link>
</Col>
</Row>
</FormContainer>
)
}
export default LoginScreen
When I remove FormContainer and replace it with a div the LoginScreen info shows up but without the styling. Otherwise it is blank with no issues in the Console. My other components seem to to show some stuff, but not the text.
Any help would be amazing.
Thanks!

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.

react-hook-form onSubmit not triggered

import React, { useState } from "react";
import FileBase64 from "react-file-base64";
import { useDispatch } from "react-redux";
import { makeStyles } from "#material-ui/core/styles";
import { TextField, Select, Input, MenuItem, Button } from "#material-ui/core";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "#hookform/resolvers/yup";
import * as yup from "yup";
import { updatePost } from "../actions/post";
const useStyles = makeStyles((theme) => ({
textField: {
marginBottom: theme.spacing(2),
},
buttons: {
marginTop: theme.spacing(2),
},
}));
const tags = ["fun", "programming", "health", "science"];
const postSchema = yup.object().shape({
title: yup.string().required(),
subtitle: yup.string().required(),
content: yup.string().min(20).required(),
tag: yup.mixed().oneOf(tags),
});
const EditPostForm = ({ history, post, closeEditMode }) => {
const dispatch = useDispatch();
const [file, setFile] = useState(post?.image);
const { register, handleSubmit, control, errors, reset } = useForm({
resolver: yupResolver(postSchema),
});
const onSubmit = (data) => {
const updatedPost = {
_id: post._id,
...data,
image: file,
};
dispatch(updatePost(post._id, updatedPost));
reset();
setFile(null);
closeEditMode();
};
const classes = useStyles();
return (
<div>
<form noValidate autoComplete="off" onSubmit={handleSubmit(onSubmit)}>
<TextField
id="title"
label="Başlık"
name="title"
variant="outlined"
className={classes.textField}
size="small"
{...register('title')}
error={errors?.title ? true : false}
fullWidth
defaultValue={post?.title}
/>
<TextField
id="subtitle"
label="Alt Başlık"
name="subtitle"
variant="outlined"
className={classes.textField}
size="small"
{...register('subtitle')}
error={errors?.subtitle ? true : false}
fullWidth
defaultValue={post?.subtitle}
/>
<Controller
render={({field}) => (
<Select
{...field}
input={<Input />}
className={classes.textField}
fullWidth
>
{
tags.map((tag, index) => (
<MenuItem {...field} key={index} value={tag}>
{tag}
</MenuItem>
))
}
</Select>
)}
name='tag'
control={control}
error={errors?.tag ? true : false}
defaultValue={tags[0]}
/>
<TextField
id="content"
label="İçerik"
name="content"
multiline
size="small"
{...register('content')}
rows={16}
className={classes.textField}
variant="outlined"
error={errors?.content ? true : false}
fullWidth
defaultValue={post?.content}
/>
<FileBase64 multiple={false} onDone={({ base64 }) => setFile(base64)} />
<div className={classes.buttons}>
<Button color="primary" variant="outlined" onClick={closeEditMode}>
Vazgeç
</Button>{" "}
<Button color="secondary" variant="outlined" type="submit" >
Kaydet
</Button>
</div>
</form>
</div>
);
};
export default EditPostForm;
I have EditPostForm component, component doesn't give any error but when I tried to submit my form onSubmit function is not triggered.
I used react-hook-form to create my form and I used material UI components inside form.
When I Click button which has type submit does not trigger onSubmit function which is called inside of handleSubmit. Why onSubmit is not triggered?
onSubmit isn't triggered because you may have form errors
You can get errors from formState object (const { formState } = useForm(...))
And then use error={formState.errors?.content ? true : false} in your code
https://react-hook-form.com/api/useform/formstate
See an example here
https://codesandbox.io/s/keen-burnell-2yufj?file=/src/App.js
You need to pass onSubmit and onError both.
Like this:
onPress={handleSubmit(onSubmit, onErrors)}
I faced the same error, the problem was that, my register were Boolean and my input was string, and since the value was not required It didn't show errors until I figure out the problem and change register from Boolean to string

Categories