how to add icon to Autocomplete TextField MUI v5 in Reactjs? - javascript

Well, I made an autocomplete using the code below and tried to display its icon after selecting each item, but it didn't work!
import { useState } from 'react'
import { TextField,InputAdornment ,Autocomplete,Box} from '#mui/material';
import v1 from './v1.svg';
import v3 from './v2.svg';
import v4 from './v3.svg';
import v4 from './v4.svg';
function App() {
const [useicon ,setUseicon]=useState(v1);
const options=[
{'label':"تتر","icon":v1},
{'label':"بایننس",'icon':v2},
{'label':"بی اس دی",'icon':v3},
{'label':"دای",'icon':v4},
]
return (
<div>
<Autocomplete
options={options}
getOptionLabel={(option) => option.label}
onChange={(e,value)=>{setUseicon(value['icon'])}}
sx={{width:"300px"}}
renderOption={(props, option) => (
<Box component="li" {...props}>
<img src={option.icon} style={{width:"50px",height:"50px"}} alt={option.label} />
{option.label}
</Box>
)}
renderInput={(params) => (
<TextField
{...params}
inputProps={{
...params.inputProps,
startAdornment: <InputAdornment position='end'>
<img src={useicon} />
</InputAdornment> ,
}}
/>
)}
/>
</div>
)
}
export default App;
some notes:
1-All the imports were correct and there is no problem
2-In the same way, the icon is shown in the TextField Component.
3-If there is a typo, know that it was in this post and not in the program itself
Please help because it is very important for me.

Replace inputProps with InputProps.
InputProps={{
...params.InputProps,
startAdornment: (
<InputAdornment position='end'>
<img src={useicon} />
</InputAdornment>
),
}}
inputProps is the attributes You apply to the input Dom element, but the InputProps is the properties that You assign to the MUI Input element.
More data Here.

Related

React-Hook Form useFieldArray: Adding Material-UI Select shows no data in the console

I have a Material-UI Select inside a nested useFieldArray. Every time I'll add the Material-UI Select and submit it to the form, whatever values that were entered in the form will not be saved and do not log in to the console. Also, I keep on having this warning when I do not have a ref anymore.
Link to codesandbox where codes are complete here: https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/nestedFieldArray.js:0-1722
Warning: Invalid value for prop refer on tag. Either remove it
from the element, or pass a string or number value to keep it in the
DOM.
Material-UI select
import { InputLabel, MenuItem, FormControl, Select } from "#mui/material";
const Size = ({ name, refer, defaultValue }) => {
return (
<FormControl fullWidth variant="filled">
<InputLabel id="Size Label">Size</InputLabel>
<Select
labelId="Size"
id="size"
name={name}
label="Product"
refer={refer}
defaultValue={defaultValue}
>
<MenuItem value="S">Small</MenuItem>
<MenuItem value="M">Medium</MenuItem>
<MenuItem value="L">Large</MenuItem>
</Select>
</FormControl>
);
};
export default Size;
I'm using the Size here:
import React from "react";
import { useFieldArray } from "react-hook-form";
import Size from "./Drop_drowns/Size";
import { TextField } from "#mui/material";
export default ({ nestIndex, control, register }) => {
const { fields, remove, append } = useFieldArray({
control,
name: `test[${nestIndex}].nestedArray`
});
return (
<div>
{fields.map((item, k) => {
return (
<div key={item.id} style={{ marginLeft: 20 }}>
<label>Colors:</label>
<Size
name={`test[${nestIndex}].nestedArray[${k}].field1`}
refer={register({ required: true })}
defaultValue={item.field1}
style={{ marginRight: "25px" }}
/>
{/* <input
name={`test[${nestIndex}].nestedArray[${k}].field1`}
ref={register({ required: true })}
defaultValue={item.field1}
style={{ marginRight: "25px" }}
/> */}
<TextField
name={`test[${nestIndex}].nestedArray[${k}].field2`}
refer={register()}
defaultValue={item.field2}
/>
<TextField
name={`test[${nestIndex}].nestedArray[${k}].field3`}
refer={register()}
defaultValue={item.field3}
/>
<button type="button" onClick={() => remove(k)}>
Delete Colors
</button>
</div>
);
})}
<button
type="button"
onClick={() =>
append({
field1: "field1",
field2: "field2"
})
}
>
Add Colors
</button>
<hr />
</div>
);
};

react-admin - add Multiple records at one in Create view

I'm trying to create multiple posts at once in a react-admin Create view. It's similar to one-to-many whereby one author can create multiple posts at once in a Create component in react-admin. I haven't found a working way when using a TabbedForm.The reason being when you fill a single field, it autocompletes on the other TabbedForm since the TextInput relate to the same source name.I would like to know how to handle multiple form inputs using React-Admin Tabs without having to render the inputs twice.
Here is the source code
import * as React from "react";
import {
List,
Create,
ArrayInput,
SimpleFormIterator,
TextInput,
DateInput,
Datagrid,
TextField,
DateField,
Admin,
Resource,
TabbedForm,
FormTab
}
from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
//read ops
export const PostList = (props) => (
<List {...props}>
<Datagrid>
<TextField source="id" />
<TextField source="title" />
<TextField source="body" />
<DateField source="published_at" />
</Datagrid>
</List>
);
//create ops
export const PostCreate = (props) => (
<Create {...props}>
<TabbedForm>
<FormTab label="single Post">
<TextInput variant="outlined" source="title" />
<TextInput variant="outlined" source="body" options={{ multiLine: true }} />
<DateInput variant="outlined" label="Publication date" source="published_at" defaultValue={new Date()} />
</FormTab>
<FormTab label="Multiple Post">
<TextInput variant="outlined" source="title" />
<TextInput variant="outlined" source="body" options={{ multiLine: true }} />
<DateInput variant="outlined" label="Publication date" source="published_at" defaultValue={new Date()} />
<ArrayInput source="posts">
<SimpleFormIterator>
<TextInput variant="outlined" label="title" source="title" />
<TextInput variant="outlined" label="body" source="teaser" />
<DateInput variant="outlined" label="Publication date" source="published_at" />
</SimpleFormIterator>
</ArrayInput>
</FormTab>
</TabbedForm>
</Create>
);
//main
const App = () => (
<Admin title="ubeezy blog" dataProvider={jsonServerProvider('https://jsonplaceholder.typicode.com')}>
<Resource name="posts" list={PostList} create={PostCreate} />
</Admin>
);
export default App;
PostCreate component is relevant here since I have Single and Multiple post creations of which when creating a single post, it picks up the input details and reflects on Multiple post creation tab fields.
Interactive demo at codesandbox:
https://codesandbox.io/s/ra-multiple-form-creation-1ecmi?file=/src/App.js
I'd appreciate the help.

add space between 2 fields in the same row

How can I add some space between the two text fields in the same row? I tried adding margins and paddings, even display flex in the css but nothing seems to work for me.
import "./styles.css";
import TextField from "#material-ui/core/TextField";
import "./App.css";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div className="labels">
<TextField id="filled-basic" label="First Label" variant="filled" />
<TextField id="filled-basic" label="Second Label" variant="filled" />
</div>
</div>
);
}
Codesandbox: https://codesandbox.io/s/wild-cache-7cjow?file=/src/App.js:0-471
Check how this is done in Material ui docs.
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import TextField from '#material-ui/core/TextField';
const useStyles = makeStyles((theme) => ({
root: {
'& > *': {
margin: theme.spacing(1),
width: '25ch',
},
},
}));
export default function BasicTextFields() {
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Standard" />
<TextField id="filled-basic" label="Filled" variant="filled" />
<TextField id="outlined-basic" label="Outlined" variant="outlined" />
</form>
);
}
When I put margin inline it works fine:
<TextField id="filled-basic" style={{ marginRight: "10px" }} label="First Label" variant="filled" />
Why don't you use Grid? As for different screen sizes it will help you.
Here is how to get your desired output:
<Grid container spacing={1} alignItems="center">
<Grid item sm={6} xs={12}>
<TextField
label="Field 1"
name="f1"
type="text"
variant="outlined"
/>
</Grid>
<Grid item sm={6} xs={12}>
<TextField
label="Field 2"
name="f2"
type="text"
variant="outlined"
/>
</Grid>
</Grid>
This works:
.MuiInputBase-root {
margin: 10px;
}
When I look at the elements in developer tools the classes and ids don't seem to render as one would expect given how they are coded in the component. For example the inputs seem to be wrapped in an element that has the class MuiInputBase-root.
Using that as the selector in the CSS and applying the style to it worked.

Material UI - The textfield in the search bar doesn't get clicked when search icon is clicked

To show the search Icon on TextField, this is what I've been doing:
<TextField
size="small"
id="searchCandidate"
data-testid="searchCandidate"
label={textLabel}
variant="outlined"
fullWidth
onChange={onChange}
onBlur={onBlur}
className={classes.searchBar}
InputLabelProps={{
classes: {
focused: classes.cssFocused
}
}}
InputProps={{
classes: {
root: classes.cssOutlinedInput,
focused: classes.cssFocused,
notchedOutline: classes.notchedOutline
},
endAdornment: inputAdornment
}}
/>
And
const inputAdornment = showSearchIcon ? (
<InputAdornment>
<IconButton style={{padding: 0}} aria-label={textLabel}>
<SearchIcon data-testid="search_message" />
</IconButton>
</InputAdornment>
) : null;
So a search icon appears in the textfield due to the inputAdornment. However, if I click on the icon, the input doesn't get clicked. I should probably provide an onclick to IconButton and handle thorugh that. Or is there a simpler way to do this?

How would i get the selected from my autocomplete box using material ui library in react

Below is the code which uses an external library called material ui and implements a search box with autocomplete. when a value is selected a input tag gets created and has value:"selected value", how would i access the value to be able to do something with it.
import React from "react";
import TextField from "#material-ui/core/TextField";
import Autocomplete from "#material-ui/lab/Autocomplete";
class ContractsList extends React.Component {
render() {
const contracts = this.props.contracts;
return (
<div>
<div className="searchbar">
<h1>All Aboard</h1>
</div>
<div className="search-bar">
<Autocomplete
id="search-bar-id"
disableClearable
options={contracts.map(contract => contract.name)}
renderInput={params => (
<TextField
{...params}
label="Search contract"
margin="normal"
variant="outlined"
InputProps={{ ...params.InputProps, type: "search" }}
/>
)}
/>{" "}
</div>
</div>
);
}
}
export default ContractsList;
im trying to get the selected value from the input field but its not working
The onChange callback is being called once you change the value of the autocomplete (change of value is basically once you select/remove items from your list).
onChange={(ev, value) => {
console.log(value);
}}
Here is a working example as part of the autocomplete:
<Autocomplete
onChange={(ev, value) => {
console.log(value);
}}
id="combo-box-demo"
options={autoCompleteItems}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />}
/>
You can see a codesandbox here.

Categories

Resources