Enlarge placeholder lineHeight and fontSize of InputBase in material UI - javascript

I am a newbie of material UI and I am using it for my website
I want the placeholder of the inputbase in material ui to increase their lineHeight and fontSize but I don't know to access to the placeholder API to customize it, please help me out
this is my current screen
this is what I expected
this is my code
import React, { useContext } from 'react';
import { InputBase, Grid, makeStyles } from '#material-ui/core';
import { SearchBoxContext } from '../../providers/SearchBoxContextProvider';
const useStyles = makeStyles((theme) => ({
largeSearchBoxContainer: (props) => {
return {
[theme.breakpoints.up('sm')]: {
textAlign: 'left',
display: 'none',
},
};
},
hideSearchBox: {
display: 'none',
},
InputBaseStyle: {
'& $placeholder': {
fontSize: '88px',
lineHeight: '88px',
},
},
}));
export default function LargeSearchBox() {
const classes = useStyles();
var { openSearchBox } = useContext(SearchBoxContext);
return (
<>
<Grid
className={classes.largeSearchBoxContainer}
container
xs={12}
sm={12}
direction="row"
justify="flex-start"
alignItems="center"
>
<Grid item xs={12} sm={12} className={openSearchBox ? null : classes.hideSearchBox}>
<InputBase
placeholder="Search…"
className={classes.InputBaseStyle}
fullWidth
autoFocus
margin
inputProps={{ 'aria-label': 'search' }}
/>
</Grid>
</Grid>
</>
);
}

You need to override the .MuiInputBase-input CSS via the input Rule name.
In my example below, I took advantage of the classes object property as explained in the documentation.
const useStyles = makeStyles((theme) => ({
InputBaseStyle: {
"&::placeholder": {
fontSize: "88px",
lineHeight: "88px"
},
height: "120px"
}
}));
<InputBase
placeholder="Search…"
// className={classes.InputBaseStyle} you can omit this
fullWidth
autoFocus
margin
inputProps={{ "aria-label": "search" }}
classes={{
input: classes.InputBaseStyle
}}
/>
CodeSandBox: https://codesandbox.io/s/restless-dawn-b5xvv?file=/src/App.js
InputBase CSS Rule names: https://material-ui.com/api/input-base/#css

Related

How to pass data from input field to parent component using context API in React?

I have an input field in child component. If you type in valid wallet address it should display wallet balance in parent component.
I don't know how to pass that e.target.value we are reading from input field.
I tried to do this function in parent component - Dashboard.
const [walletBalance, setWalletBalance] = useState('');
const getWalletBalance = async () => {
try {
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:3000');
for (const wallet of dummyWallets) {
const balance = await web3.eth.getBalance(wallet.address);
console.log(balance);
const balanceConvertedFromWeiToEth = await Web3.utils.fromWei(balance, 'ether');
const shortenedBalance =
balanceConvertedFromWeiToEth.length >= 10
? balanceConvertedFromWeiToEth.slice(0, 10)
: balanceConvertedFromWeiToEth;
setWalletBalance(shortenedBalance);
}
} catch (error) {
console.error(error);
throw new Error('No wallet found');
}
};
render (
<p>Wallet balance: {walletBalance}</p>
and then pass this function down to child component with input field (need to prop drill 3 times for that) and in child component say:
const [inputText, setInputText] = useState('');
const handleInputChange = (e) => {
setInputText(e.target.value);
if (inputText === wallet.address) {
getWalletBalance()
}
};
render (
<input value={inputText} onChange={handleInputChange} />
)
It didn't work. No errors. Just nothing happens.
Then I thought that I need to do the other way around: Instead of trying to pass getWalletBalance() down as props, I need to read data from input field and pass that data to parent component, because parent needs to have access to the input field and read from it to be able to display wallet balance in parent.
I've also tried to create context:
import React, { useState, createContext } from 'react';
import { dummyWallets } from '../mocks/dummyWallets';
import Web3 from 'web3';
export const WalletContext = createContext();
// eslint-disable-next-line react/prop-types
export const TransactionProvider = ({ children }) => {
const [inputText, setInputText] = useState('');
const [walletBalance, setWalletBalance] = useState('');
const handleInputChange = async (e) => {
setInputText(e.target.value);
const web3 = new Web3(Web3.givenProvider || 'ws://localhost:3000');
for (const wallet of dummyWallets) {
if (inputText === wallet.address) {
const balance = await web3.eth.getBalance(wallet.address);
console.log(balance);
const balanceConvertedFromWeiToEth = await Web3.utils.fromWei(balance, 'ether');
const shortenedBalance =
balanceConvertedFromWeiToEth.length >= 10
? balanceConvertedFromWeiToEth.slice(0, 10)
: balanceConvertedFromWeiToEth;
setWalletBalance(shortenedBalance);
}
}
};
return (
<WalletContext.Provider
value={{ walletBalance, handleInputChange, inputText, setInputText,
setWalletBalance }}>
{children}
</WalletContext.Provider>
);
};
Then pass handleInputChange to onChange in child component and inputText as value, then use walletBalance in parent component.
All context things walletBalance, handleInputChange, inputText, setInputText and setWalletBalance threw undefined error.
Here is child component consuming data from context:
import React, { FC, useState, useContext } from 'react';
import { Formik, Form, Field } from 'formik';
import { Button, InputAdornment, Box, Grid } from '#material-ui/core';
import TextField from '#eyblockchain/ey-ui/core/TextField';
import { Search } from '#material-ui/icons';
import SvgEthereum from '../../../images/icon/Ethereum';
import { makeStyles } from '#material-ui/styles';
import { Theme } from '#material-ui/core';
import { dummyWallets } from '../../../shared/mocks/dummyWallets';
import Web3 from 'web3';
import { WalletContext } from '../../../shared/context/WalletContext';
const etherIconBorderColor = '#eaeaf2';
const useStyles = makeStyles((theme: Theme) => ({
etherIconGridStyle: {
padding: '16px 0 0 0'
},
etherIconStyle: {
fontSize: '220%',
textAlign: 'center',
color: theme.palette.primary.light,
borderTop: `solid 1px ${etherIconBorderColor}`,
borderBottom: `solid 1px ${etherIconBorderColor}`,
borderLeft: `solid 1px ${etherIconBorderColor}`,
padding: '5px 0 0 0',
[theme.breakpoints.down('sm')]: {
fontSize: '150%',
lineHeight: '43px'
}
},
buttonStyle: {
paddingTop: theme.spacing(2)
},
searchIconStyle: {
color: theme.palette.primary.light
}
}));
const onSubmitHandler = () => {
return;
};
const SearchInputForm: FC<any> = (props) => {
const { walletBalance, handleInputChange, inputText } = useContext(WalletContext);
const classes = useStyles();
return (
<Formik
onSubmit={onSubmitHandler}
initialValues={{ name: '' }}
render={({ values }) => {
return (
<Form>
<Grid container>
<Grid item xs={1} className={classes.etherIconGridStyle}>
<Box className={classes.etherIconStyle}>
<SvgEthereum />
</Box>
</Grid>
<Grid item xs={11}>
<Field
required
name="name"
placeholder={props.placeholdervalue}
value={inputText}
component={TextField}
onChange={handleInputChange}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<Search fontSize="large" className={classes.searchIconStyle} />
</InputAdornment>
)
}}
/>
</Grid>
<Grid item xs={12}>
<Box
display="flex"
justifyContent="flex-end"
alignItems="flex-end"
className={classes.buttonStyle}>
<Button type="submit" variant="contained" color="secondary" size="large" disabled>
Create Alert
</Button>
</Box>
</Grid>
</Grid>
</Form>
);
}}
/>
);
};
export default SearchInputForm;
Here is parent component where I pull walletBalance from context:
const Dashboard: FC<any> = () => {
const { walletBalance } = useContext(WalletContext);
const classes = useStyles();
return (
<>
<Container maxWidth={false} className={classes.dashboardContainer}>
<Grid>
<Box data-testid="alert-page-heading">
<Typography variant="h3">Alerts</Typography>
</Box>
<Box data-testid="alert-page-subheading">
<Typography className={classes.subHeadingStyle}>
Monitor the Web 3.0 for interesting blockchain events
</Typography>
</Box>
</Grid>
<Grid container spacing={4}>
<Grid item xs={12} sm={8}>
<Box className={classes.dashboardCard}>
<Box className={classes.searchBox}>
<SearchTabs />
</Box>
<Box
sx={{
display: 'flex',
justifyContent: 'space-between'
}}>
<Box
sx={{
height: '60%',
padding: '1%',
fontSize: 20
}}>
<a href="http://localhost:3000/" className={classes.backToAlertsLink}>
Back to my alerts
</a>
<p className={classes.boldText}>Recent transactions</p>
</Box>
<Box sx={{ height: '60%', padding: '4%', fontSize: 20 }}>
<span>Wallet Balance</span>
<span className={classes.balanceNumber}>{walletBalance} ETH</span>
</Box>
</Box>
</Box>
</Grid>
<Grid item xs={12} sm={4}>
<Box className={classes.dashboardCard}>
<Box sx={{ height: '60%', padding: '2%', fontSize: 20, fontWeight: 'bold' }}>
Top 10 alerts
</Box>
</Box>
</Grid>
</Grid>
</Container>
</>
);
};
export default Dashboard;
The problem is that I pull handleChange from context and apply to input field in child component to read the value from the input and then pull walletBalance from context in parent but that walletBalance is not updated (doesn't contain input value in it).
Can someone please share knowledge on how to read data from child component input field and display something from that in parent component?
Any advice is appreciated. Thank you.

Specify ::after style with MaterialUI Grid

I read Flex-box: Align last row to grid and trying to see if this will work for me too:
.grid::after {
content: "";
flex: auto;
}
but not sure how to specify this in JS styles that I use in MaterialUI:
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
paper: {
height: 140,
width: 140,
},
control: {
padding: theme.spacing(2),
},
fullName: {
marginRight: '3px'
}
}));
Like how do I add after to a MaterialUI Grid?
<Grid className={classes.root} container justify="space-around" spacing={2}>
<CompanyList companies={companies} data-test-id="companyList" />
</Grid>
You could use like below:
const useStyles = makeStyles((theme) => ({
grid: {
// --- some styles
'&::after': {
// --- some style
}
},
}));
It's similar task as to add pseudo element to material-ui component
content attribute needed to be double quoted
Working exammple
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
"&::after": {
content: '""',
width: 40,
height: 40,
backgroundColor: "cyan",
color: "white"
}
},
}));
export default function Material() {
const classes = useStyles();
return (
<div>
<h1>Material</h1>
<Grid
className={classes.root}
container
justify="space-around"
spacing={2}
>
<CompanyList companies={companies} data-test-id="companyList" />
</Grid>
</div>
);
}

React <Switch> is not getting updated or changing its state

Hey guys I am learning react and have a form to edit book details. I am using django in the backend. I am not able to update the e-book which is a switch to turn on and off according to whether e-book is available or not. The switch works fine, but no data is being changed in the database. I am confused on how to work with the switch and saw lots of resources saying different things which is quite difficult to understand. Rest of the fields are getting updated correctly. Can someone tell me what changes I have to make in this switch to make it work??
code
import React, {useEffect, useState} from 'react'
import axiosInstance from '../../axios';
import { useForm, Controller } from 'react-hook-form';
//MaterialUI
import Button from '#material-ui/core/Button';
import CssBaseline from '#material-ui/core/CssBaseline';
import TextField from '#material-ui/core/TextField';
import Grid from '#material-ui/core/Grid';
import Typography from '#material-ui/core/Typography';
import { makeStyles } from '#material-ui/core/styles';
import Container from '#material-ui/core/Container';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import Switch from '#material-ui/core/Switch';
import Select from '#material-ui/core/Select';
import InputLabel from '#material-ui/core/InputLabel';
import MenuItem from '#material-ui/core/MenuItem';
import FormControl from '#material-ui/core/FormControl';
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
bookformbody: {
display: "flex",
backgroundColor: "#ffff",
height: "100vh",
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(3),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
function BookEdit() {
const initialFormData = Object.freeze({
id: '',
summary: '',
published_date: '',
e_book: false,
});
const [formData, updateFormData] = useState(initialFormData);
useEffect(() => {
axiosInstance.get('api/books/details/view/').then((res) => {
updateFormData({
...formData,
['summary']: res.data.summary,
['published_date']: res.data.published_date,
['e_book']: res.data.e_book,
});
console.log(res.data);
});
}, [updateFormData]);
const handleChange = (e) => {
if(e.target.name === "e_book"){
return(
updateFormData({
...formData,
[e.target.name]: e.target.checked
})
)
}
updateFormData({
...formData,
// Trimming any whitespace
[e.target.name]: e.target.value
});
};
const onSubmit = (data) =>{
let formData = new FormData();
formData.append('summary', data.summary);
formData.append('published_date', data.published_date);
formData.append('e_book', data.e_book);
axiosInstance.put('api/books/details/edit/', formData);
} ;
const classes = useStyles();
const { register, handleSubmit, control, errors } = useForm();
return (
<>
<Header />
<div className={classes.bookformbody}>
<SideBar />
<Container component="main" maxWidth="sm">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Edit Book Details
</Typography>
<form className={classes.form} noValidate onSubmit={handleSubmit(onSubmit)}>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="summary"
label="Book Summary"
name="summary"
autoComplete="summary"
value={formData.summary}
onChange={handleChange}
inputRef={register({maxLength: 1000})}
multiline
rows={4}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
type="date"
label="Published Date"
name="published_date"
autoComplete="published_date"
value={formData.published_date}
onChange={handleChange}
inputRef={register({required: true})}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<InputLabel id="e-book-switch">E-Book</InputLabel>
<Controller
name="e_book"
control={control}
as={
<Switch size="small"
id="e-book-switch"
type="checkbox"
name="e_book"
onChange={handleChange}
// inputRef={register}
value={formData.e_book}
checked={formData.e_book}
/>
}
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Update
</Button>
</form>
</div>
</Container>
</div>
</>
)
}
export default BookEdit;
You are passing props to Switch directly, but what you should do is to use Controller props, and Controller will then pass it down to Switch:
<Controller as={Switch} value={formData.e_book} ... />
Otherwise you need to use render, not as
This is actually described pretty good here:
https://react-hook-form.com/api/#Controller
UPDATE
Here is the sandbox where it is working fine with above changes - https://codesandbox.io/s/kind-nash-s94v0
What i did there is simply this:
<Controller
name="e_book"
control={control}
render={(props) => {
return (
<Switch
size="small"
id="e-book-switch"
type="checkbox"
name="e_book"
onChange={handleChange}
// inputRef={register}
value={formData.e_book}
checked={formData.e_book}
/>
);
}}
/>
You are initializing the value as a string at the beginning of BookEdit(). Try to set initialFormData like this:
const initialFormData = Object.freeze({
id: '',
summary: '',
published_date: '',
e_book: false,
});

Global state pattern using React Hooks + Context API not working on mobile devices (iOS)

So I followed this tutorial on YouTube. Component re-render seems to work perfectly on the desktop (Microsoft Edge) when global state changes, but it doesn't work when I test it on my phone (iPhone 8, tested on both safari and Google Chrome).
Here is the code inside App.js:
function App() {
const contentStyle = makeStyles((theme) => ({
container: {
padding: '5px',
width: '100% !important',
height: '100% !important',
margin: 0,
flexGrow: 1,
},
chart_container: {
width: '100%', height: '100%', position: 'relative'
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
height: 'inherit',
},
alternative: {
backgroundColor: '#ffffff'
},
maps: {
minHeight: '350px',
maxHeight: '60vh',
width: '100%',
height: '100%'
}
}));
const classes = contentStyle()
const { state } = useContext(Context)
return (
<React.Fragment>
<Navbar title='MyApp' />
<Grid container spacing={3} className={classes.container}>
<Grid item xs={12}>
<Paper elevation={5} className={classes.paper + ' ' + classes.alternative}>
<Grid container spacing={2}>
<Grid item xs={6}>
<Maps className={classes.maps} elevation={5} />
</Grid>
<Grid item xs={6}>
<BridgeCard name={state.bridgeName} address={state.bridgeAddress} image={state.bridgeImage} />
</Grid>
</Grid>
</Paper>
</Grid>
<Grid item xs={12}>
<GraphTabs />
<Paper elevation={5} className={classes.paper + ' ' + classes.alternative}>
<canvas style={{ width: '100%', height: '60vh' }} id="chart1" />
</Paper>
</Grid>
</Grid>
</React.Fragment>
)
}
Here is the context.js:
import { createContext } from 'react'
const Context = createContext({})
export default Context
Inside index.js
const Index = () => {
const theme = createMuiTheme({ palette, themeName });
const store = useGlobalState();
return (
<Context.Provider value={store}>
<React.StrictMode>
<MuiThemeProvider theme={theme}>
<App />
</MuiThemeProvider>
</React.StrictMode>
</Context.Provider>
)
}
Inside useGlobalState.js:
import { useState } from 'react';
const useGlobalState = () => {
const [state, setState] = useState({
})
const actions = (action) => {
const { type, payload } = action;
switch (type) {
case 'setState':
return setState(payload)
default:
return state;
}
}
return { state, actions }
}
export default useGlobalState;
Am I missing something or it is something to do with mobile browsers? I did a debug attempt and I got that the component doesn't re-render when the global state changed. Any suggestion?

How to change material-ui slider thumb style when it's disabled

I am able to modify the Slider style using withStyles:
const CustomSlider = withStyles(theme => ({
disabled: {
color: theme.palette.primary.main
},
thumb: {
height: 24,
width: 24,
},
}))(Slider);
but the height and width of the thumb is only applied when the component is disabled={false}.
is there a simple way to change the slider height and width on disabled={true}?
Demo:
https://codesandbox.io/s/slide-thumb-size-gxb4g?file=/demo.js
Reason
The style is been overridden by className Mui-disabled
You can see the color will keep.
How to solve it
Override the style of MuiSlider-thumb or Mui-disabled
One option: use MUI className nesting selector
"& .MuiSlider-thumb": {
height: 24,
width: 24
}
Notice withStyles attributes refer to the CSS API, you can use className + style hooks instead to customize the className which is not exposed by the CSS API like that
Full code:
import React from "react";
import Slider from "#material-ui/core/Slider";
import Paper from "#material-ui/core/Paper";
import { withStyles, makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles(theme => ({
margin: {
margin: theme.spacing(10),
"& .MuiSlider-thumb": {
height: 24,
width: 24
}
}
}));
const CustomSlider = withStyles(theme => ({
disabled: {
color: theme.palette.primary.main
},
thumb: {
// color: "red"
}
}))(Slider);
export default function MyCustomSlider() {
const classes = useStyles();
return (
<div>
<Paper className={classes.margin}>
<CustomSlider
defaultValue={[10, 15]}
min={0}
max={20}
valueLabelDisplay="on"
disabled={true}
/>{" "}
<CustomSlider
defaultValue={[5, 7]}
min={0}
max={20}
valueLabelDisplay="on"
disabled={false}
/>{" "}
</Paper>
</div>
);
}
Update
For withStyles
const styles = theme =>
createStyles({
margin: {
margin: theme.spacing(10)
},
thumb: {
"& .MuiSlider-thumb": {
height: 24,
width: 24
}
}
});
function MyCustomSlider(props) {
// const classes = useStyles();
return (
<div>
<Paper className={props.classes.margin}>
<Slider
defaultValue={[10, 15]}
min={0}
max={20}
valueLabelDisplay="on"
disabled={true}
className={props.classes.thumb}
/>{" "}
<Slider
defaultValue={[5, 7]}
min={0}
max={20}
valueLabelDisplay="on"
disabled={false}
/>{" "}
</Paper>
</div>
);
}
export default withStyles(styles)(MyCustomSlider);
disabled: {
"& .MuiSlider-thumb ": {
display: "none",
},
"& .MuiSlider-track": {
backgroundColor: "#e0e0e0",
},
},
This is withStyle solution , where user can change the styling of slider and its sub component.

Categories

Resources