Uncaught TypeError: Cannot read properties of undefined (reading '8') - javascript

This is my first time posting and I am a junior Frontend developer so please go easy on me.
This has me very confused and I've looked, tested and for some reason the Inputlabel from Material UI (ver. 5) is not working on this side of the website I am developing. I used inputlabel and date picker on the home page and they work with no problems. But suddenly trying to make a user profile form... Well, it's starting to give me trouble. Literally copying what is in the documentation and still get this issue.
When I click on the Input everythig on the page disappears. Opening the Chrome Inspector gives me the error that's in the title. And I am truly clueless. Posting my code to see if someone cand lend me a bit of help here. Thank you in advance.
import React from 'react';
import { TextField } from '#mui/material';
import { Grid } from '#mui/material';
import { Box } from '#mui/system';
import { Container } from '#mui/material';
import InputLabel from '#mui/material/InputLabel';
import MenuItem from '#mui/material/MenuItem';
import FormControl from '#mui/material/FormControl';
import Select from '#mui/material/Select';
import { DatePicker } from "#mui/lab";
import { LocalizationProvider } from "#mui/lab";
import AdapterDateFns from '#mui/lab/AdapterDateFns';
//import '../User/components/styles/UserStyles.scss';
const UserProfileTxt = () => {
//DOB picker
const [dob, setDob] = React.useState(new Date())
//Nationality Picker
const [nationality, setNationality] = React.useState('');
const handleChange = (event) => {
setNationality(event.target.value);
};
return (
<Container>
<Grid container>
<Grid sx={{ flexDirection: 'column', display: 'flex' }}>
<TextField sx={{mt:'0.5rem', mb:'0.5rem'}} variant='outlined' label='Nombre' />
<TextField sx={{mt:'0.5rem', mb:'0.5rem'}} variant='outlined' label='Apellido' />
<TextField sx={{mt:'0.5rem', mb:'0.5rem'}}variant='outlined' label='E-mail' />
<Box sx={{ minWidth: 120, mt:'0.5rem', mb:'1rem' }}>
<FormControl fullWidth>
<InputLabel id="NationalityUSERHIKLUB">Nacionalidad</InputLabel>
<Select
labelId="Nacionalidad"
id="Naccionalidad"
value={nationality}
label="Nationalidad"
onChange={handleChange}
>
<MenuItem value={1}>Ten</MenuItem>
</Select>
</FormControl>
</Box>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Seleccióna fecha de Nacimiento"
value={dob}
onChange={(newValue) => {
setDob(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</Grid>
<Grid>
</Grid>
</Grid>
</Container>
);
};
export default UserProfileTxt;

Okay. I solved my own question.
This is probably a bug, but I didn't add this to the original question because I seriously didn't think it was going to be related. Despite that, I am going to share it in case someone is having issues as well.
So, this form I am doing is inside a <Tabs/> component, which I costumized using <ThemeProvider/> and <CreateTheme/>. Started basically breaking my code down seeing where the error could stem from. Finally, I noticed that it could be the <ThemeProvider/> on the tabs. And sure enough, once I removed both <ThemeProvider/> and <CreateTheme/> The date picker and dropdown menu were working fine.
Sorry I didn't address it before but I seriously did not think it was going to be related to the issue at hand
So, long story short:
DO NOT USE THEMEPROVIDER WHEN USING TABS ON MUI VER 5. USE STYLED COMPONENTS INSTEAD AND GET THE SAME RESULT WITH A LOT LESS ISSUES. I suppose there is some sort of conflict with that and the tabs component.
Thanks to anyone who answered.

Related

breakpoints not working in MUI v5 and react project

I'm trying to use breakpoints for responsive design in my page, but it dosent really seem to work. Whenever i apply any breakpoint, the whole page goes blank.
Here's my code:-
Styles.js
import { makeStyles } from "#mui/styles";
const useStyles = makeStyles((theme) => ({
title: {
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
},
}));
export default useStyles;
Header.jsx
import React from 'react';
import { Autocomplete } from '#react-google-maps/api';
import { AppBar, Toolbar, Typography, InputBase, Box } from '#mui/material';
import SearchIcon from '#mui/icons-material/Search';
import useStyles from './styles';
const Header = () => {
const classes = useStyles();
return (
<>
<AppBar position='static'>
<Toolbar className={classes.toolbar}>
<Typography variant='h5' className={classes.title}>
Travel Advisor
</Typography>
{/* Box acts as Div */}
<Box display='flex'>
<Typography variant='h6' className={classes.title}>
Explore new places
</Typography>
{/* <Autocomplete> */}
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<InputBase placeholder='Search...' classes={{ root: classes.inputRoot, input: classes.inputInput }} />
</div>
{/* </Autocomplete> */}
</Box>
</Toolbar>
</AppBar>
</>
)
}
export default Header;
Before applying breakpoints :-
Before breakpoint
After applying breakpoints :-
After breakpoint
Make sure that you created breakpoints correctly.
https://mui.com/material-ui/customization/breakpoints/
And check if you have wrapped your app in ThemeProvider.
And I want to note that #mui/styles is deprecated. Perhaps this problem may be related to this.
https://mui.com/system/styles/basics/
⚠️ #mui/styles is the legacy styling solution for MUI. It depends on JSS as a styling solution, which is not used in the #mui/material anymore, deprecated in v5. If you don't want to have both Emotion & JSS in your bundle, please refer to the #mui/system documentation which is the recommended alternative.
⚠️ #mui/styles is not compatible with React.StrictMode or React 18.
Dont use it on newly created app.

The code is correct, but an img file stored locally is not displayed - React

On this project, I'm using the MUI library
I have an image on this route /assets/images/banner.png (I've already verified the route and the name of the image is the correct one) The code should be correctly showing me the "banner.png" but it isn't
This is my component HeroBanner.js
import React from 'react';
import { Box, Stack, Typography, Button} from '#mui/material';
import HeroBannerImage from '../assets/images/banner.png';
function HeroBanner() {
return (
<Box sx={{
mt: { lg:'212', xs:'70px' },
ml: { sm: '50px' }
}} position='relative' p='20px'>
<Typography color='#FF2625' fontWeight='600' fontSize='26px'>
Fitness Club
</Typography>
<Typography fontWeight={700}
sx={{ fontSize: { lg: '44px', xs:'40px'}}}>
Sweat, Smile <br /> and Repeat
</Typography>
<Typography fontSize='22px' lineHeight='35px' mb={3}>
Check out the most effective exercises
</Typography>
<Button variant='contained' color='error' href='#exercises'>Explore Exercise</Button>
<img src={HeroBannerImage} alt="hero-banner" className="hero-banner-img" />
</Box>
)
}
export default HeroBanner
I tried your code, and it worked for me. Maybe try importing another image or something. Make sure to check the folder names and image name.
This is the link for the tested code : Codesandbox
There are many options
here is a simple one
<img src={require('./path/to/image.svg').default} />

React Fetch API Being Called 2 Times on page load

React Fetch API Being Called 2 Times on page load, I don't know what is missing in this code or what I am doing wrong. I have faced this problem from the morning,
I really appreciate any help you can provide.
React Fetch API Being Called 2 Times on page load, I don't know what is missing in this code or what I am doing wrong. I face this problem from the morning,
I really appreciate any help you can provide.
import React, { useState, useEffect } from 'react'
import axios from 'axios';
import { Grid, Paper, TextField } from '#mui/material'
import PersonOutlineIcon from '#mui/icons-material/PersonOutline';
function FormApi() {
//Mui fileds and paper style
const paperStyle = { padding: '50px ', width: 550, margin: '50px auto' }
//Fetch data from api
const [userx, setUserx] = useState([{data:null,support:null}]);
const url = 'https://reqres.in/api/users/2';
useEffect(()=>{
//debugger
const fetchData = async () =>{
await axios.get(`${url}`)
.then((response) =>{
setUserx(response.data)
}).catch((error)=>{
console.log(error)
})
}
fetchData();
}
,[]);
return (
<Grid container spacing={2} style={paperStyle}>
<Grid align='center' >
<Paper elevation={20} >
<Grid align='center'>
<h2 style={{padding:'10px' ,background: "#000080", color: 'white' }}>
<PersonOutlineIcon large style={{fontSize:'80%'}} />User Details</h2>
</Grid>
<form>
<img style={{width:"20%"}} src={userx.data ? userx.data.avatar : ''}/>
<h1 style={{color:'#000080'}}>{userx.data ? userx.data.first_name : ''}
{userx.data ? userx.data.last_name : ''}</h1>
<Grid container >
<Grid item xs={6} >
<h2 style={{color:'white', background: "purple"}}>Contact Info</h2>
<TextField value={userx.data ? userx.data.id : ''} variant="standard"
/>
<TextField value={userx.data ? userx.data.email : ''}
variant="standard" />
</Grid>
<Grid item align='left' xs={6} style={{marginBottom:'40px'}}>
<h2 style={{color:'white', background: "purple"}}>Social Link</h2>
<TextField value={userx.support ? userx.support.url : ''}
variant="standard" />
<TextField value={userx.support ? userx.support.text : ''}
variant="standard" />
</Grid>
</Grid>
</form>
</Paper>
</Grid>
</Grid>
)
}enter code here
export default FormApi
It's because React renders components 2 times in the development environment. To avoid this, you can comment out the <React.StrictMode> tag in index.js file.
Rendering twice will only appear in the development environment and StrictMode has many benefits for development:
Identifying components with unsafe lifecycles
Warning about legacy string ref API usage
Warning about deprecated findDOMNode usage
Detecting unexpected side effects
Detecting legacy context API
Ensuring reusable state
So it's better to keep the <React.StrictMode> tag if it doesn't affect your normal development work.
See also: React StrictMode
This is normal behaviour in React 18. It will only be done on development environments and when StrictMode is enabled and will not be a problem in your production Build.
A bit annoying, but nothing really to worry about. There is a workaround which you can learn more about in a in-depth answer here:
React 18, useEffect is getting called two times on mount
You can handle it with useRef hook:
const renderAfterCalled = useRef(false);
useEffect(() => {
if (!renderAfterCalled.current) {
// your API call func
}
renderAfterCalled.current = true;
}, []);
as much as I know, this issue is caused by the HTTTP client sending 2 request, one to the route path "/" and the other to "/favicon.ico"
make this change :
useEffect(()=>{
checkLocation();
//your code
,[]);
after some revision
try this
function FormApi() {
//Mui fileds and paper style
const paperStyle = { padding: '50px ', width: 550, margin: '50px auto' }
//Fetch data from api
const [userx, setUserx] = useState([{data:null,support:null}]);
const url = 'https://reqres.in/api/users/2';
//debugger
const fetchData = async () =>{
await axios.get(`${url}`)
.then((response) =>{
setUserx(response.data)
}).catch((error)=>{
console.log(error)
})
}
useEffect(()=>{
fetchData();
}
,[]);

TypeError: Object(...) is not a function error in useAccordianToggle

I'm new to react. I'm using react-bootstrap and trying to create an accordion having more than 20 cards in it. Each card header has a right/down pointing caret icon. I want to toggle the icon to point down or point right based on whether the card body is collapsed or not. So, i tried implementing the example from react-bootstrap website Custom Toggle with Expansion Awaremess and I'm getting the above error at the line
const decoratedOnClick = useAccordionToggle(
eventKey,
() => callback && callback(eventKey),
);
The complete code is below.
import React, {useContext} from 'react';
import Accordion from 'react-bootstrap/Accordion';
import useAccordionToggle from 'react-bootstrap/AccordionToggle';
import AccordionContext from 'react-bootstrap/AccordionContext';
import Card from 'react-bootstrap/Card';
import 'bootstrap/dist/css/bootstrap.min.css';
function ContextAwareToggle({ children, eventKey, callback }) {
const currentEventKey = useContext(AccordionContext);
const decoratedOnClick = useAccordionToggle(
eventKey,
() => callback && callback(eventKey),
);
const isCurrentEventKey = currentEventKey === eventKey;
return (
<button
type="button"
style={{ backgroundColor: isCurrentEventKey ? 'pink' : 'lavender' }}
onClick={decoratedOnClick}
>
{children}
</button>
);
}
function App() {
return (
<Accordion defaultActiveKey="0">
<Card>
<Card.Header>
<ContextAwareToggle eventKey="0">Click me!</ContextAwareToggle>
</Card.Header>
<Accordion.Collapse eventKey="0">
<Card.Body>Hello! I'm the body</Card.Body>
</Accordion.Collapse>
</Card>
<Card>
<Card.Header>
<ContextAwareToggle eventKey="1">Click me!</ContextAwareToggle>
</Card.Header>
<Accordion.Collapse eventKey="1">
<Card.Body>Hello! I'm another body</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
);
}
export default App;
I even tried setting my own context like below
import React from 'react';
export default React.createContext(null);
But I'm still getting the same error!
Also, i have come across examples of using css to achieve this but i do not have a choice of using different libraries like fontawesome. Is there a better way to implement what I'm looking for? Thanks.
I figured it out and it was a silly mistake. i had to use {} around useAccordianToggle import statement as below.
import { useAccordionToggle } from 'react-bootstrap/AccordionToggle';

Problems with React Router/Hoook

Update (new changes):
So now I pretty much converted my code to a functional component however it is as if nothing is being returned from the API, or perhaps I am not "mounting" correctly? I get the error " TypeError: Cannot read property 'map' of undefined" meaning nothing is being returned but I'm not sure why. Help?
Old post (I had previously tried to use a hook in a a class component):
I'm pretty brand new to react and recently I have been getting this error from when trying to navigate to a page on click of a card media (using material ui). So I pretty much follow the instruction to push to history the route to the page I want to navigate to via a function and call that function when I click the media card. Below is my code and the error I get. Do you have any idea why I might be having an issue with this?
My updated code
import Card from '#material-ui/core/Card';
import CardMedia from '#material-ui/core/CardMedia';
import Grid from '#material-ui/core/Grid';
import Container from '#material-ui/core/Container';
import {getItems} from "../Network/network_utility";
import {useHistory} from "react-router-dom";
import {makeStyles} from '#material-ui/core/styles';
import React, {useState, useEffect} from "react";
const useStyles = makeStyles(theme => ({
icon: {
marginRight: theme.spacing(2),
},
heroContent: {
padding: theme.spacing(8, 0, 6),
},
cardGrid: {
paddingTop: theme.spacing(6),
paddingBottom: theme.spacing(3),
position: "fixed"
}
}));
export default function Items() {
let history = useHistory();
const classes = useStyles();
const useFeaturedItems = () => {
const [featured_items, setFeaturedItems] = useState([]);
useEffect(() => {
getItems(1).then(response => setFeaturedItems(response["data"]))}, []);
return featured_items;
};
return (
<div>
<Container className={classes.cardGrid} maxWidth="lg">
<Grid container spacing={6}>
{useFeaturedItems().map((card, index) => (
<Grid item key={index} xs={16} sm={4} md={2}>
<Card raised={false} style={{height: "30vh", width: "20vh"}}>
<CardMedia
component="img"
src={card["thumbnail"]}
style={{height: "25vh", width: "20vh"}}
onClick={history.push("/item")}
>
</CardMedia>
<div style={{paddingLeft: "10px", paddingTop: "10px"}}>
<text style={{
whiteSpace: "nowrap",
overflow: "hidden",
display: "block",
textOverflow: "ellipsis"
}}>
{card["title"]}
</text>
</div>
</Card>
</Grid>
))}
</Grid>
</Container>
</div>
);
}
As I can see you are using hook inside a class component. It is not possibile
how use hook
You can’t use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.
In class component you need to use the HOC withRouter. After that you can access the history through props with this.props.history

Categories