Currently doing a project with Material-UI's library. Im having issues with styling.
I'm pretty new to ReactJS or just JS in general, and doing this project is my first time I am interacting with it.
Any help will be greatly appreciated!
I am unable to style my text box like the way example they gave.
this is my code:
class AppBase extends Component {
constructor(props) {
super(props);
this.state = {
...INITIAL_STATE
};
}
classes = useStyles;
render() {
return (
<Container component="main" maxWidth="md">
<div className={this.classes.root}>
<TextField required id="standard-required" label="Required" defaultValue="Hello World" />
<TextField disabled id="standard-disabled" label="Disabled" defaultValue="Hello World" />
<TextField
id="standard-password-input"
label="Password"
type="password"
autoComplete="current-password"
/>
<TextField
id="standard-read-only-input"
label="Read Only"
defaultValue="Hello World"
InputProps={{
readOnly: true,
}}
/>
<TextField
id="standard-number"
label="Number"
type="number"
InputLabelProps={{
shrink: true,
}}
/>
<TextField id="standard-search" label="Search field" type="search" />
<TextField
id="standard-helperText"
label="Helper text"
defaultValue="Default Value"
helperText="Some important text"
/>
</div>
</Container>
);
}
}
This example I have taken is from: https://codesandbox.io/s/51hrm
I have copied the useStyles exactly at the top, and this is what I get:
How the code looks like
This is not the only instance where I am facing this issue with calling useStyles in my components.
Calling 'classes = useStyles;' works on some useStyles but not the others, I am really at lost for this.
Because of the way the other pages has been done, I will not consider using Functions like the example given.
Thank you in advance!
If you're copying the useStyles function from the example provide, then it needs to be called as a function. Right now, you're just assigning the function to the classes variable, but never executing the function. So just change the one line of code as follows:
const classes = useStyles();
And you will execute the useStyles function and assign the result to the classes variable. At that point, you'll be able to use the classes constant in your jsx to style the components, like the example:
<form className={classes.root} ...></form>
useStyles hook can only be called inside a functional component. You have to change your class component to functional component if you want to use useStyles hook.
I have created a live sandbox for you to play around also: https://codesandbox.io/s/loving-bouman-47bek?fontsize=14&hidenavigation=1&theme=dark
The code below should work fine:
import React from "react";
import ReactDOM from "react-dom";
import { Container, TextField } from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles({
root: {
background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
border: 0,
borderRadius: 3,
boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
color: "white",
height: 48,
padding: "0 30px"
}
});
function App() {
const classes = useStyles();
return (
<Container component="main" maxWidth="md">
<div className={classes.root}>
<TextField
required
id="standard-required"
label="Required"
defaultValue="Hello World"
/>
<TextField
disabled
id="standard-disabled"
label="Disabled"
defaultValue="Hello World"
/>
<TextField
id="standard-password-input"
label="Password"
type="password"
autoComplete="current-password"
/>
<TextField
id="standard-read-only-input"
label="Read Only"
defaultValue="Hello World"
InputProps={{
readOnly: true
}}
/>
<TextField
id="standard-number"
label="Number"
type="number"
InputLabelProps={{
shrink: true
}}
/>
<TextField id="standard-search" label="Search field" type="search" />
<TextField
id="standard-helperText"
label="Helper text"
defaultValue="Default Value"
helperText="Some important text"
/>
</div>
</Container>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Also I would hight suggest you to start using functional components instead of class components since the functional components are the future of React.
Related
Is there a way to make it so that the <Input /> doesn't close on click? Currently, if I click inside the input, the menu just closes. I have the same setup as the original poster. I've tried playing around with closeOnSelect="false" and that didn't seem to work. Any advice would be greatly appreciated.
Here is the example in CodeSandbox form:
https://codesandbox.io/s/chakra-menuitem-as-input-forked-9ue4n
import {
Box,
Button,
ChakraProvider,
Input,
Menu,
MenuButton,
MenuItem,
MenuList,
useMenuItem,
} from '#chakra-ui/react';
import React from 'react';
const navigationKeys = ['ArrowUp', 'ArrowDown', 'Escape'];
const MenuInput = props => {
const { role, ...rest } = useMenuItem(props);
return (
<Box px="3" role={role}>
<Input
placeholder="Enter value"
size="sm"
{...rest}
onKeyDown={e => {
if (!navigationKeys.includes(e.key)) {
e.stopPropagation();
}
}}
/>
</Box>
);
};
function App() {
return (
<ChakraProvider>
<Menu>
<MenuButton as={Button}>Button</MenuButton>
<MenuList>
<MenuInput />
<MenuItem>Option 1</MenuItem>
<MenuItem>Option 2</MenuItem>
</MenuList>
</Menu>
</ChakraProvider>
);
}
export default App;
Add closeOnSelect={false} to the menu component to stop the menu closing when clicking on the MenuInput.
<Menu closeOnSelect={false}>
<MenuButton as={Button}>Button</MenuButton>
<MenuList>
<MenuInput />
<MenuItem>Option 1</MenuItem>
<MenuItem>Option 2</MenuItem>
</MenuList>
</Menu>
I tried to search for the answer but I am not getting anything to solve it.
I am loading my image using require.context as you can see in the code but it's not getting loaded. It used to work perfectly before in previous versions of react js. Now I am using react version 17.0.1. There are no errors in the console. If I import the image and use it in the src it works fine. I have also tried to change the images with some previous images used in previous projects (using react version 16.x.x) which are working fine there. I am creating react app using npx-create-react-app. Path to image is correct as in case of incorrect path "module named xxx not found error occurs".
Current behavior:
Image not showing up instead alt value is showing up.
Desired behavior:
Image should show up instead of alt value.
import React, { Component } from "react";
import commonStyles from "../css/common.module.css";
import loginStyles from "../css/login.module.css";
import { TextField, Button, Paper, Typography } from "#material-ui/core";
class Login extends Component {
state = {
userName: "",
password: "",
error: "",
};
render() {
const images = require.context("../images", true);
return (
<div
className={`${loginStyles.root} d-flex justify-content-center align-items-center ${commonStyles.bg}`}
>
<Paper
classes={{
root: `${commonStyles.paper} mt-2`,
}}
elevation={3}
>
<div className={`${loginStyles.child}`}>
<div className={`d-flex justify-content-center align-items-center`}>
<img
src={images(`./Shahmeer.png`)}
alt={`Shahmeer Avenue Logo`}
width="100"
height="100"
/>
</div>
<Typography
classes={{
root: `font-weight-bold`,
}}
variant="h5"
gutterBottom
>
Login
</Typography>
<form noValidate autoComplete="off">
<TextField
classes={{
root: `${commonStyles.textField}`,
}}
onChange={(e) => this.handleChange(e)}
id={"userName"}
label={"User Name"}
variant="outlined"
error={this.state.error ? true : false}
helperText={this.state.error}
value={this.state["userName"]}
/>
<TextField
classes={{
root: `${commonStyles.textField}`,
}}
onChange={(e) => this.handleChange(e)}
id={"password"}
label={"Password"}
variant="outlined"
error={this.state.error ? true : false}
helperText={this.state.error}
value={this.state["password"]}
/>
<div className={`w-100 d-flex justify-content-end mt-2`}>
<Button variant="contained" color="primary">
Login
</Button>
</div>
</form>
</div>
</Paper>
</div>
);
}
}
export default Login;
snapshot of browser:
You should use the default property for the images:
<img
src={images(`./Shahmeer.png`).default}
alt={`Shahmeer Avenue Logo`}
width="100"
height="100"
/>
I'm new to materialUI. This is how I'm using a simple input field which is outlined and has an icon. But as my background is dark, I need the color of the icon, the border and the text in a lighter color, e.g. grey.
What is the materialUI way to do this?
import Input from '#material-ui/core/OutlinedInput'
import InputAdornment from '#material-ui/core/InputAdornment'
import AccountCircle from '#material-ui/icons/AccountCircle'
<Input
name='username'
type='text'
placeholder='Username'
startAdornment={
<InputAdornment position='start'>
<AccountCircle />
</InputAdornment>
}
/>
One way you could achieve this is with the following code:
import React from "react";
import Input from "#material-ui/core/OutlinedInput";
import InputAdornment from "#material-ui/core/InputAdornment";
import AccountCircle from "#material-ui/icons/AccountCircle";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles(theme => ({
root: {
padding: theme.spacing(4),
backgroundColor: theme.palette.common.black
},
input: {
color: theme.palette.common.white,
"&:hover $notchedOutline": {
borderColor: theme.palette.grey[400]
},
"&$focused $notchedOutline": {
borderColor: theme.palette.grey[400]
},
},
notchedOutline: {
borderColor: theme.palette.grey[400]
},
focused: {},
adornedStart: {
color: theme.palette.grey[400]
}
}));
export default function Demo() {
const classes = useStyles();
return (
<div className={classes.root}>
<Input
classes={{
root: classes.input,
notchedOutline: classes.notchedOutline,
focused: classes.focused,
adornedStart: classes.adornedStart
}}
name="username"
type="text"
placeholder="Username"
startAdornment={
<InputAdornment position="start">
<AccountCircle />
</InputAdornment>
}
/>
</div>
);
}
CodeSandbox
In my example I've used Material UI's own styling solution. But there are also a lot of other ways to solve this. You could also use styled components for example.
Material UI has a great documentation. You can read a lot about styling solutions on this page. You could also change the default theme which changes the styles for all input fields. Or you could use the dark version of the Material UI theme which is already built in.
I am using this module by HackerOne: https://reactdatepicker.com
After installing and importing the module to my Project i decided to pick the Select time component from the site.
My Code
import React, { Component } from "react";
import { Form, Button } from "react-bootstrap"
import DatePicker from "react-datepicker"
export default class AddEventModal extends Component {
constructor(props) {
super(props)
this.state = {
date: new Date()
}
}
render() {
return (
<Form>
<Form.Group controlId="formBasicEmail">
<Form.Label>Title <span style={{ color: "red" }}>*</span></Form.Label>
<Form.Control type="text" placeholder="Enter a Title" className="col-6" />
<Form.Text className="text-muted">
Enter a Title for your Event.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Description</Form.Label>
<Form.Control type="text" placeholder="Enter a Description" className="col-6" />
</Form.Group>
<DatePicker
selected={this.state.date}
onChange={newDate => this.setState({ date: newDate })}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
timeCaption="time"
dateFormat="MMMM d, yyyy h:mm aa"
/>
<Form.Group controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>
<Button variant="success" type="submit">
Submit
</Button>
</Form>
);
}
}
My Output
https://i.stack.imgur.com/2L1Rv.png
It shouldn't be like this... The site has the working demo. What am I doing wrong?
EDIT: Answer is in the comments. I was missing a css import
Seems like I was missing a css import. Too bad the site didn't mention this clearly.
import "react-datepicker/dist/react-datepicker.css"
I have designed a form with validation using TypeScript Material UI and Formik. I want a material UI Icon to appear in my textfield area, here's my code:
import React from 'react'
import { Formik, Form, FieldAttributes,useField} from 'formik'
import { TextField } from '#material-ui/core'
import CalendarTodayIcon from '#material-ui/icons/CalendarToday'
import * as yup from 'yup'
import './MainInfo.css'
const MyTextField: React.FC<FieldAttributes<{}>> = ({
placeholder,type,className,style,
...props
}) => {
const [field, meta] = useField<{}>(props);
const errorText = meta.error && meta.touched ? meta.error : "";
return (
<div className='container'>
<TextField
placeholder={placeholder}
className={className}
style={style}
type={type}
{...field}
helperText={errorText}
error={!!errorText}
id="outlined-basic"
variant="outlined"
/>
</div>
);
};
export function MainInfo() {
return (
<div>
<Formik
validateOnChange={true} validationSchema={validationSchema} initialValues={{ Title: '', ActivationDate: '', ExpirationDate: '', DirectManager: '', HRBP: '' }} onSubmit={(data) => {
console.log(data)
}}
>
{({values, errors}) => (
<Form id='my-form' >
<div>
<label className='label'>عنوان</label>
<div >
<MyTextField style={{width:'60%'}} placeholder='طراح' name='Title' type='input' />
</div>
...
</div>
</Form>
)}
</Formik>
</div>
)
}
but the problem is that I can not add a new Icon property or InputProp since <FieldAttributes<{}>> doesnt accept it. how can I define a new property for the FieldAttributes or fix this issue?
Use the TextField Props InputProps to customize the input field
And use startAdornment, endAdornment to customize the prefix/suffix
Finally use icon inside InputAdornment would be fine
import { TextField, InputAdornment } from "#material-ui/core";
import ExpandLess from "#material-ui/icons/ExpandLess";
import ExpandMore from "#material-ui/icons/ExpandMore";
<TextField
id="standard-basic"
label="Standard"
InputProps={{
startAdornment: (
<InputAdornment position="start">
<ExpandLess />
</InputAdornment>
),
endAdornment: (
<InputAdornment position="end">
<ExpandMore />
</InputAdornment>
)
}}
/>
Refer:
MUI TextField Props API: InputProps, startAdornment, endAdornment
MUI InputInputAdornment Props API
online demo: https://stackblitz.com/edit/gzlbzm