How to set multi value to autocomplete component in reactjs - reactjs

I need to set multi selected value to autocomplete in reactjs. I'm using Material-UI components in my project.
F.e you can see above. First data is coming first user and second data is coming from another user. I want to fill in the value like that. Then, user can remove selected values or add new values.
If you can do it with dummy data, I can use with data from database. All i need how to do this.
import React from 'react';
import Chip from '#material-ui/core/Chip';
import Autocomplete from '#material-ui/lab/Autocomplete';
import { makeStyles } from '#material-ui/core/styles';
import TextField from '#material-ui/core/TextField';
const useStyles = makeStyles((theme) => ({
root: {
width: 500,
'& > * + *': {
marginTop: theme.spacing(3),
},
},
}));
export default function Multi({callbackFromMultiSelect,reference,favBooks}) {
const classes = useStyles();
return (
<div className={classes.root}>
<Autocomplete
multiple
id="tags-standard"
options={favBooks}
getOptionLabel={(option) => (option.name)}
// onClick={()=>alert('test')}
onChange={(event, value) =>callbackFromMultiSelect({value:value,reference:reference})}
// defaultValue={[top100Films[1]]}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
label="favBooks"
placeholder="favBooks"
/>
)}
/>
</div>
);
}
And my parent component
import React from 'react'
import AutoCompleteTest from './AutoComplete'
export const Test = () => {
const callbackFromMultiSelect = (item) => {
console.log(item)
}
const favBooks=[
{name:"LOTR",from:"a",to:"a"},
{name:"GOT",from:"b",to:"b"},
{name:"HP",from:"c",to:"c"}
]
return (
<div className={'mainStore'}>
Test
<AutoCompleteTest callbackFromMultiSelect={callbackFromMultiSelect} reference={'test'} favBooks={favBooks}/>
<br />
<AutoCompleteTest callbackFromMultiSelect={callbackFromMultiSelect} reference={'test'} favBooks={favBooks}/>
</div>
)
}

I've made a codesandbox
https://codesandbox.io/s/wizardly-saha-gor3s?file=/src/App.js
You basicly have to make the component a controlled component.
https://material-ui.com/components/autocomplete/#playground
You can do this by using the 'getOptionSelected' prop

Related

How to use 'classes' to customize compound components in Mui?

I am trying to override the Mui styles by using the classes prop.
For example, I would like to override the InputLabel color of the TextField component.
I would like to use one definition of makeStyles that will set all css rules, starting at the root (TextField) and overriding whatever I want in the hierarchy (for example, the InputLabel when focused), when passing it to the component in the classes prop.
How is it done?
import * as React from "react";
import TextField from "#mui/material/TextField";
import makeStyles from "#mui/styles/makeStyles";
const useStyles = makeStyles({
root: {
color: "yellow",
label: {
color: "brown"
}
}
});
export default function Input() {
const classes = useStyles();
return (
<TextField
classes={classes}
id="outlined-basic"
label="Outlined"
variant="outlined"
/>
);
}
Answer
import * as React from "react";
import TextField from "#mui/material/TextField";
import makeStyles from "#mui/styles/makeStyles";
const useStyles = makeStyles({
root: {
"& .MuiInputBase-input": {
color: 'red',
padding: "0.2rem"
},
},
});
export default function Input() {
const classes = useStyles();
return (
<TextField
InputProps={{ classes }}
/>;
);
}
codesandbox
The classes prop in MUI gives you access to the CSS Rule Names for a component. When you're using this prop, check the API spec for that component. The CSS Rule Names are at the bottom of the page.
https://mui.com/api/text-field/#css
For this component, there is only 1 rule available (root), so this will (I think) have the same effect as just using className.
What you probably want to do is use the InputProps prop instead. The Input component has way more CSS Rules you can target: https://mui.com/api/input/#css
So, I think you probably want to do this:
<TextField
InputProps={{ classes }}
id="outlined-basic"
label="Outlined"
variant="outlined"
/>
EDIT to help answer comment:
I don't think you need to target InputBase, as I believe you can target input instead. To target the input CSS Rule, just change the root key to input:
import * as React from "react";
import TextField from "#mui/material/TextField";
import makeStyles from "#mui/styles/makeStyles";
const useStyles = makeStyles({
input: {
color: 'red',
padding: "0.2rem"
},
});
export default function Input() {
const classes = useStyles();
return (
<TextField
InputProps={{ classes }}
/>;
);
}
The CSS rules in the docs are sensitive to the keys in the object you pass.
The best way I found is to use the Mui v5 sx property.
(makeStyles is deprecated - https://mui.com/guides/migration-v4/#2-use-tss-react)
(input signifies the rule in https://mui.com/api/input-base/#css)
import * as React from "react";
import TextField from "#mui/material/TextField";
export default function Input() {
const classes = useStyles();
return (
<TextField
sx={{
"& input":
{ padding: "0rem",color: "blue" }
}}
/>
);
}

How can I apply Proptypes properly on my React component?

I have the following component:
import React from 'react';
import PropTypes from 'prop-types';
import IconButton from '#material-ui/core/IconButton';
import TextField from '#material-ui/core/TextField';
import ClearIcon from '#material-ui/icons/Clear';
const InputSearch = ({ onClearSearch, onSearch, ...searchProps }) => {
const { id, value } = searchProps;
const onClear = (event) => {
onClearSearch(event, id);
};
return (
<TextField
id={id}
name={id}
onChange={onSearch}
value={value}
InputProps={{
endAdornment: value && (
<IconButton
className={classes.searchIcon}
onClick={onClear}
>
<ClearIcon fontSize={'small'} color={'primary'} />
</IconButton>
),
}}
/>
);
};
InputSearch.propTypes = {
onClearSearch: PropTypes.func.isRequired,
};
export default InputSearch;
As you can see, I'm trying to apply a required validation using propTypes. But then, when I try to use the component without the onClearSearch function, no error is being shown:
<InputSearch
value={searchBy}
onSearch={handleSearch}
/>
So what I'm doing wrong?
Your code is right... you can open developer tool of chrome by pressing F12 -> go to Console and you can see prop type error
for more detail you can see
https://blog.logrocket.com/validating-react-component-props-with-prop-types-ef14b29963fc/
If you want your project give prop-type error in terminal then you have to setup eslint in your project.

react How to hide the Card when another location is pressed

Developed with react and typescript.
Now the card is shown or hidden when you click on the div tag.
I want to hide the Card when it is displayed, even if another place other than the div tag is pressed.
import React, { FunctionComponent, useState } from 'react';
import { Card } from 'components/atoms/Card';
import { Display } from 'components/atoms/Display';
const Test: FunctionComponent = () => {
const [isDisplay, setIsDisplay] = useState(false);
const onClick = () => {
setIsDisplay(!isDisplay);
};
return (
<>
<div onClick={onClick} style={{ width: '100px', height: '100px' }}>
display Card
</div>
<Display enabled={isDisplay}>
<Card width={100} height={100}></Card>
</Display>
</>
);
};
export default Test;
Try this in your onClick method. It looks like you need to access the current state's value and update it.
setIsDisplay(state => !state);
It's explained here in the React docs.
https://reactjs.org/docs/hooks-reference.html#functional-updates

Style a component's [aria-checked="true"] using Material UI's makeStyle

I have a check box (not a Material-UI checkbox) that I'd like to style using it's aria-checked="true" attribute via makeStyles. I see in the Material-UI docs that you can style pseudo selectors as such:
'&:hover': { /* … */ },
But I haven't been able to make this work for the aria attribute? Is this possible? If so, how?
The syntax for attribute selectors is largely the same as in CSS. & is used to refer to the generated class (classes.myCheckboxStyles in my example below) and then further selectors can be added within the quotes (e.g. "&[aria-checked=true]").
Below is a working example demonstrating the syntax:
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles({
myCheckboxStyles: {
border: "1px black solid",
color: "white",
"&[aria-checked=true]": {
backgroundColor: "blue"
}
}
});
export default function Checkboxes() {
const classes = useStyles();
const [checked, setChecked] = React.useState(false);
return (
<div>
<span
onClick={() => setChecked(!checked)}
aria-checked={checked}
className={classes.myCheckboxStyles}
>
X
</span>
</div>
);
}
I've tried to use aria-checked="true" to activate MUI checkbox, but it doesn't work. So, in my view, you should try using onMouseEnter to activate MUI checkbox. You can try this:
import React from "react";
import Checkbox from "#material-ui/core/Checkbox";
export default function Checkboxes() {
const [checked, setChecked] = React.useState(false);
const handleChange = event => {
setChecked(event.target.checked);
};
return (
<div>
<Checkbox
checked={checked}
onMouseEnter={() => setChecked(true)}
onChange={handleChange}
inputProps={{ "aria-label": "primary checkbox" }}
/>
</div>
);
}

Ant-Design React-Native Search Bar Cancel Button cannot hide itself when pressed

I'm trying to make the Cancel button on the right of the search bar hide when it gets press. I tried to use to showCancelButton prop but it is not working. Ant-Design React-Native Docs Link
This is the link to the issue reproduction repo https://github.com/kvnlee777/antd-rn-issue
react-native version 0.61.4
ios simulator version 12.4
import React, {useState} from 'react';
import { Alert, View} from 'react-native';
import { SearchBar } from '#ant-design/react-native';
const SearchBarDemo = () => {
const [value, setValue] = useState('');
const [showCancel, setShowCancel] = useState(true);
const onChange = (currentValue) => {
setValue(currentValue);
}
const clear = () => {
setValue('');
setShowCancel(false);
}
return (
<View style={{ marginTop: 30}}>
<SearchBar
value={value}
placeholder="Search products, brands"
onSubmit={value => Alert.alert(value)}
onCancel={clear}
onChange={onChange}
cancelText='Cancel'
showCancelButton={showCancel}
/>
</View>
);
};
export default SearchBarDemo;
You are using strings for true and false. The string 'false' evaluates to true.
Replace 'true' and 'false' with true and falseand it should work

Resources