Unable to Write in MUI SearchBar - javascript

I am able to display a Material UI search bar but I am unable to type anything into it. How can I fix this?
I have tried using the code snippets given as current answers but they give errors in my existing code.
import React, { Component, useState } from 'react'
import SearchBar from 'material-ui-search-bar';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
import PermanentDrawerLeft from '../../components/drawer/drawer';
const userSearchPage = () => (
<div>
<PermanentDrawerLeft></PermanentDrawerLeft>
<MuiThemeProvider>
<DropDownMenu >
<MenuItem style={ {fontSize: "20px" } } primaryText="Search By"/>
<MenuItem value={1} style={ {fontSize: "20px" } } primaryText="First Name" />
<MenuItem value={1} style={ {fontSize: "20px" } } primaryText="Last Name" />
</DropDownMenu>
</MuiThemeProvider>
<SearchBar
onChange={() => console.log('onChange')}
onRequestSearch={() => console.log('onRequestSearch')}
style={{
margin: '0 auto',
maxWidth: 800
}}
/>
</div>
);
export default userSearchPage;

Thats because you are missing the state of your SearchBar component, you need to keep a state for searchBar input value.
<SearchBar
value={this.state.value}
onChange={(newValue) => this.setState({ value: newValue })}
onRequestSearch={() => console.log('onRequestSearch')}
style={{
margin: '0 auto',
maxWidth: 800
}
/>

You can use a hook and have the value there and then update it on changes made to the field.
import React, { useState } from 'react'
...
const [text, setText] = useState("");
...
<SearchBar
onChange={e => setText(e.target.value)}
value={text}
onRequestSearch={() => console.log('onRequestSearch')}
style={{
margin: '0 auto',
maxWidth: 800
}}
/>

import React, { useState } from "react";
import SearchBar from "material-ui-search-bar";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import DropDownMenu from "material-ui/DropDownMenu";
import MenuItem from "material-ui/MenuItem";
import PermanentDrawerLeft from "../../components/drawer/drawer";
const userSearchPage = () => {
const [text, setText] = useState("");
return (
<div>
<PermanentDrawerLeft />
<MuiThemeProvider>
<DropDownMenu>
<MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
<MenuItem
value={1}
style={{ fontSize: "20px" }}
primaryText="First Name"
/>
<MenuItem
value={1}
style={{ fontSize: "20px" }}
primaryText="Last Name"
/>
</DropDownMenu>
</MuiThemeProvider>
<SearchBar
value={text}
onChange={value => {
setText(value);
console.log("onChange");
}}
onRequestSearch={() => console.log("onRequestSearch")}
style={{
margin: "0 auto",
maxWidth: 800
}}
/>
</div>
);
};
export default userSearchPage;

Related

Why doesn't my image show on my react app page?

So i've been trying to show an image on my page with an API, but everytime I go to the page I see the image for a few seconds and after that the page refreshes and it shows an error:
Uncaught TypeError: location is undefined
I think the problem could be about the way I used my image, but i am not sure. If I console log the image it just shows the correct image name. This is the code I used:
import { Row, Col } from "react-grid-system";
import { Separator } from "#fluentui/react";
import * as React from "react";
import { useEffect, useState } from "react";
function Recipe(props) {
const axios = require('axios');
const api = axios.create({
baseURL: 'http://localhost:5000/',
timeout: 10000
})
const [recipe, setRecipe] = useState({});
const [image, setImage] = useState({});
useEffect(() => {
getRecipe()
}, [])
function getRecipe() {
api.get('/recipe/' + props.id).then(res => {
setRecipe(res.data);
setImage("https://localhost:5001/Uploads/" + res.data.image)
});
}
return (
<div>
<div>
<Row>
<Col sm={6} md={6} lg={6}>
<img style={{ width: "700px", marginTop: "20px" }} src={image} alt={"error"} />
</Col>
<Col style={{ marginTop: "20px" }} sm={6} md={6} lg={6}>
<Separator className={"Separator"} />
<h1>Naam: <div style={{ fontSize: "20px" }}>{recipe.name}</div></h1>
<h1>Ingredienten: <div style={{ fontSize: "20px" }}> {recipe.ingredients}</div>
</h1>
<h1>Macro's:
<div style={{ fontSize: "20px" }}>
<ul>
<li>Kcal: {recipe.carbs}</li>
</ul>
</div>
</h1>
<h1>Voorbereiding: <div style={{ fontSize: "12px" }}>
{recipe.preparation} </div></h1>
</Col>
</Row>
</div>
</div>
)
}
export default Recipe

How to remove border of Material UI's DatePicker?

Here is the datepicker component
import React, { Fragment, useState } from "react";
import {
KeyboardDatePicker,
MuiPickersUtilsProvider
} from "#material-ui/pickers";
import DateFnsUtils from "#date-io/date-fns";
import makeStyles from "#material-ui/styles/makeStyles";
const useStyles = makeStyles({
root: {
"& .MuiInputBase-root": {
padding: 0,
"& .MuiButtonBase-root": {
padding: 0,
paddingLeft: 10
},
"& .MuiInputBase-input": {
padding: 15,
paddingLeft: 0
}
}
}
});
function InlineDatePickerDemo(props) {
const [selectedDate, handleDateChange] = useState(new Date());
const classes = useStyles();
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
className={classes.root}
autoOk
variant="inline"
inputVariant="outlined"
label="With keyboard"
format="MM/dd/yyyy"
value={selectedDate}
InputAdornmentProps={{ position: "start" }}
onChange={(date) => handleDateChange(date)}
/>
</MuiPickersUtilsProvider>
);
}
export default InlineDatePickerDemo;
From codeSandbox Link can anyone tell how to remove border from all sides ?
Although I managed to know that .MuiInput-underline:before style class is responsible for border width but dont know where to put that class in makeStyles.
You just need to edit a bit the KeyboardDatePicker element:
Remove inputVariant="outlined"
Add
InputProps={{
disableUnderline: true
}}
CodeSandbox
in MUI you can add variant="standard" to TextField :
renderInput={(params) => <TextField variant="standard" {...params} />}
completely :
<DesktopDatePicker
inputFormat="MM/dd/yyyy"
className="mt-0 w-100"
required={required}
margin="normal"
id="date-picker-dialog"
label={label}
format="dd/MM/yyyy"
value={value}
onChange={handleDateChange}
renderInput={(params) => <TextField variant="standard" {...params} />}
/>
It's just necessary to remove inputVariant="outlined" props. So your code becomes:
<KeyboardDatePicker
className={classes.root}
autoOk
variant="inline"
label="With keyboard"
format="MM/dd/yyyy"
value={selectedDate}
InputAdornmentProps={{ position: "start" }}
onChange={(date) => handleDateChange(date)}
/>
Here your code modified.
const useStyles = makeStyles({
root: {
"& .MuiInputBase-root": {
padding: 0,
"& .MuiButtonBase-root": {
padding: 0,
paddingLeft: 10,
},
"& .MuiInputBase-input": {
padding: 15,
paddingLeft: 0
},
"& .MuiOutlinedInput-notchedOutline": {
border: 'none'
}
}
}
});

MaterialUI show an other view after onclick event

I'm completely new in MaterialUI. I'm working on my first project right now and trying to make use of templates form its page. I've loaded two .tsx files with log in view and main dashboard view. I'd like to show main dashboard view after clicking Login button on log in view. Both files have its own export default function FnName() function with const classes = useStyles(); and it seems to cause my problems. The way of using hooks is the issue here I guess. But how to pass this function to onClick handler event button? You can see my project here:
https://codesandbox.io/s/adoring-leftpad-6nwv2?file=/src/SignIn.tsx
Somebody can help?
Please check this example:
App Component
import React, {useEffect, useState} from 'react';
import SignIn from "./material-ui/signin-template/SignIn";
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import { createBrowserHistory as history} from 'history';
import MiniDrawer from "./material-ui/signin-template/Dashboard";
class App extends React.Component {
render() {
return (
<div>
<Router history={history}>
<Switch>
<Route path="/" exact component={SignIn}/>
<Route path="/dashboard" component={MiniDrawer}/>
</Switch>
</Router>
</div>
)
}
}
export default App;
SingIn Component
import React from "react";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
import TextField from "#material-ui/core/TextField";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
import Link from "#material-ui/core/Link";
import Grid from "#material-ui/core/Grid";
import Box from "#material-ui/core/Box";
import LockOutlinedIcon from "#material-ui/icons/LockOutlined";
import Typography from "#material-ui/core/Typography";
import {makeStyles} from "#material-ui/core/styles";
import Container from "#material-ui/core/Container";
import {Redirect, useHistory} from "react-router-dom";
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{"Copyright © "}
<Link color="inherit" href="https://material-ui.com/">
Your Website
</Link>{" "}
{new Date().getFullYear()}
{"."}
</Typography>
);
}
const useStyles = makeStyles(theme => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center"
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
export default function SignIn() {
const classes = useStyles();
let history = useHistory();
return (
<Container component="main" maxWidth="xs">
<CssBaseline/>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon/>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary"/>}
label="Remember me"
/>
<Button
onClick={()=>{
history.push('/dashboard')
}}
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright/>
</Box>
</Container>
);
}
Dashboard Component
import React from "react";
import clsx from "clsx";
import {
createStyles,
makeStyles,
useTheme,
Theme
} from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import Drawer from "#material-ui/core/Drawer";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import List from "#material-ui/core/List";
import CssBaseline from "#material-ui/core/CssBaseline";
import Typography from "#material-ui/core/Typography";
import Divider from "#material-ui/core/Divider";
import IconButton from "#material-ui/core/IconButton";
import MenuIcon from "#material-ui/icons/Menu";
import ChevronLeftIcon from "#material-ui/icons/ChevronLeft";
import ChevronRightIcon from "#material-ui/icons/ChevronRight";
import ListItem from "#material-ui/core/ListItem";
import ListItemIcon from "#material-ui/core/ListItemIcon";
import ListItemText from "#material-ui/core/ListItemText";
import InboxIcon from "#material-ui/icons/MoveToInbox";
import MailIcon from "#material-ui/icons/Mail";
import MapOutlinedIcon from "#material-ui/icons/MapOutlined";
import DriveEtaOutlinedIcon from "#material-ui/icons/DriveEtaOutlined";
import PeopleAltOutlinedIcon from "#material-ui/icons/PeopleAltOutlined";
import DirectionsOutlinedIcon from "#material-ui/icons/DirectionsOutlined";
import AssessmentOutlinedIcon from "#material-ui/icons/AssessmentOutlined";
import ReportProblemOutlinedIcon from "#material-ui/icons/ReportProblemOutlined";
import AccountCircleOutlinedIcon from "#material-ui/icons/AccountCircleOutlined";
import { Redirect, useHistory } from "react-router-dom";
import ExitToAppIcon from "#material-ui/icons/ExitToApp";
const drawerWidth = 240;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
display: "flex"
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
})
},
appBarShift: {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
menuButton: {
marginRight: 36
},
hide: {
display: "none"
},
drawer: {
width: drawerWidth,
flexShrink: 0,
whiteSpace: "nowrap"
},
drawerOpen: {
width: drawerWidth,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
drawerClose: {
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
overflowX: "hidden",
width: theme.spacing(7) + 1,
[theme.breakpoints.up("sm")]: {
width: theme.spacing(9) + 1
}
},
toolbar: {
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar
},
content: {
flexGrow: 1,
padding: theme.spacing(3)
}
})
);
function MiniDrawer() {
const classes = useStyles();
let history = useHistory();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, {
[classes.hide]: open
})}
>
<MenuIcon />
</IconButton>
</Toolbar>
</AppBar>
<Drawer
variant="permanent"
className={clsx(classes.drawer, {
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})}
classes={{
paper: clsx({
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})
}}
>
<div className={classes.toolbar}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === "rtl" ? (
<ChevronRightIcon />
) : (
<ChevronLeftIcon />
)}
</IconButton>
</div>
<div className={classes.toolbar} />
<div className={classes.toolbar} />
<div className={classes.toolbar} />
<IconButton
onClick={() => {
history.push("/");
}}
>
<ExitToAppIcon />
</IconButton>
<Divider />
<List>
{["Mapa", "Pojazdy", "Kierowcy", "Trasy", "Raporty", "Alerty"].map(
(text, index) => (
<ListItem
button
key={text}
onClick={event => {
console.log(event.currentTarget);
history.push("/");
}}
>
<ListItemIcon>
{index === 0 && <MapOutlinedIcon />}
{index === 1 && <DriveEtaOutlinedIcon />}
{index === 2 && <PeopleAltOutlinedIcon />}
{index === 3 && <DirectionsOutlinedIcon />}
{index === 4 && <AssessmentOutlinedIcon />}
{index === 5 && <ReportProblemOutlinedIcon />}
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
)
)}
</List>
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
<Typography paragraph />
</main>
</div>
);
}
export default MiniDrawer;
Here is the Code Sandbox

Date not updated (handleDateChange) in React Hooks using material-ui-picker

Below is the functional signup component in React. I have one particular problem with the DatePicker component. It renders correctly on the sign up form. When I click on the submit button, it does not give me the selected date but instead it sends me the initial state of the component. Other states such as fullname, password and email are updated accordingly.
To prove that the date was not updated, I tried putting "null" in the useState() and when I get the result in the database, as expected the date is of a "null" type. How do I update the initial state to the updated state?
import React, { useState, useContext, Fragment } from "react";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
import TextField from "#material-ui/core/TextField";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
import Link from "#material-ui/core/Link";
import Grid from "#material-ui/core/Grid";
import Box from "#material-ui/core/Box";
import LockOutlinedIcon from "#material-ui/icons/LockOutlined";
import Typography from "#material-ui/core/Typography";
import { makeStyles } from "#material-ui/core/styles";
import Container from "#material-ui/core/Container";
import { signup } from "./auth-api";
import DatePicker from "./DatePicker";
import Copyright from "./Copyright";
import AuthApi from "../utils/AuthApi";
import { MuiPickersUtilsProvider } from "#material-ui/pickers"; //Date picker util provider
import DateFnsUtils from "#date-io/date-fns"; // Date util library
// We can use inline-style
const style = {
background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
borderRadius: 3,
border: 0,
color: "white",
height: 48,
padding: "0 30px",
boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
};
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(3),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function SignUp() {
const classes = useStyles();
const joindate = new Date();
const [fullname, setFullname] = useState();
const [email, setEmail] = useState();
const [password, setPassword] = useState();
const [dateofbirth, setSelectedDate] = useState(new Date());
const handleOnChange = (e) => {
if (e.target.name === "fullname") {
setFullname(e.target.value);
} else if (e.target.name === "username") {
setEmail(e.target.value);
} else if (e.target.name === "password") {
setPassword(e.target.value);
}
};
const handleDateChange = (date) => {
setSelectedDate(date);
};
const authApi = React.useContext(AuthApi);
const handleSignUp = async (e) => {
e.preventDefault();
const res = await signup({
joindate,
fullname,
email,
password,
dateofbirth,
});
if (res.data.auth) {
authApi.setAuth(true);
}
//console.log(res);
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<form className={classes.form} noValidate>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
autoComplete="fname"
name="fullname"
variant="outlined"
required
fullWidth
id="fullName"
label="Full Name"
autoFocus
onChange={handleOnChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="username"
autoComplete="email"
onChange={handleOnChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={handleOnChange}
/>
</Grid>
<Grid item xs={12}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Fragment>
<DatePicker
inputVariant="outlined"
required
fullWidth
id="dob"
name="dob"
disableFuture
openTo="year"
format="dd-MM-yyyy"
label="Date of Birth"
views={["year", "month", "date"]}
value={dateofbirth}
onChange={handleDateChange}
/>
</Fragment>
</MuiPickersUtilsProvider>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
style={style}
className={classes.submit}
onClick={handleSignUp}
>
Sign Up
</Button>
<Grid container justify="flex-end">
<Grid item>
<Link href="/signin" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={5}>
<Copyright />
</Box>
</Container>
);
}

Client console error " Uncaught SyntaxError: Unexpected token '<'"

I develop reactjs app and it works fine, but When I refresh it with F5 key or refresh button, it's not working. I check the client console and the error is like this Uncaught SyntaxError: Unexpected token '<'
But in server-side console, there are no errors in it. I don't know why it is working like this.
It only shows white page.
I uploaded my full code on CodeSandbox. You can check all of my codes and problem in there.
The problem is only in /auth/login page
https://codesandbox.io/s/livetoday-9qgh8?fontsize=14
import React from "react";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
import TextField from "#material-ui/core/TextField";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
import Link from "#material-ui/core/Link";
import Grid from "#material-ui/core/Grid";
import Box from "#material-ui/core/Box";
import LockOutlinedIcon from "#material-ui/icons/LockOutlined";
import Typography from "#material-ui/core/Typography";
import { makeStyles } from "#material-ui/core/styles";
import Container from "#material-ui/core/Container";
// import "typeface-roboto";
import {
GoogleLoginButton,
GithubLoginButton
} from "react-social-login-buttons";
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{"Copyright © "}
<Link color="inherit" href="/">
Live Today
</Link>{" "}
{new Date().getFullYear()}
{"."}
</Typography>
);
}
const useStyles = makeStyles(theme => ({
"#global": {
body: {
backgroundColor: theme.palette.common.white
}
},
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center"
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
export default function SignIn() {
const classes = useStyles();
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Currently local login is not supported"
name="email"
autoComplete="email"
disabled
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
disabled
>
Sign In
</Button>
</form>
<a
href="/auth/google"
style={{ color: "inherit", textDecoration: "none" }}
>
<GoogleLoginButton />
</a>
<a
href="/auth/github"
style={{ color: "inherit", textDecoration: "none" }}
>
<GithubLoginButton />
</a>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
);
}

Categories