Text Input Placeholder Changes With Menu Item - reactjs

Have a quick question regarding dynamic placeholder text. I have a material ui select menu with 3 menu items: name, email, and phone. I want the input box next to it to change placeholder text depending on which menu item is currently selected, i.e. Search by name, search by email, search by phone. How would I go about doing this? Very new to React so I'm still learning.

you can store select's value in a react state and change the input's placeholder according to that state's value:
const [value, setValue] = React.useState("name");
return (
<>
<Select
value={value}
onChange={e => {
setValue(e.target.value);
}}
>
<MenuItem value="name">name</MenuItem>
<MenuItem value="email">email</MenuItem>
<MenuItem value="phone">phone</MenuItem>
</Select>
<input placeholder={`search by ${value}`} />
</>
);

Related

changed logic when click on Antd Tab REACT

I'm using antd version 3 and want to change the outcome onChange when Tab is clicked.
Here the picture of my desire objective enter image description here
My tab title has a checkbox. Outcome should be in this way: when user is stand at Tab1 should have a possibility to change value checkbox of Tab2 or Tab3 without setting active Tab or moving to Tab2 or Tab3. I have read that tab didn't support HOC... I tried a lot of ways to solve but didn't work out with that. event.PreventDefault / event.stopPropagation similarly result. Even if handlers like onTabClick / onChange didn't set active Tab with a new key after checked checkbox active key is old but tab is render with new information.
Here example of custom tab title component with some extract from code
<Tabs
defaultActiveKey={'Tab 1'}
onChange={(key) => onChangeHandler(key)}
onTabClick={(key: string, event: MouseEvent) => onTabClick(key, event)}
>
<TabPane
tab={<Header name={'Tab1'} />}
key={'Tab 1'}
/>
<TabPane
tab={<Header name={'Tab 2'} />}
key={'Tab 2'}
/>
<TabPane
tab={<Header name={'Tab 3'} />}
key={'Tab 3'}
/>
const Header = ({
name,
onChange,
isActive,
id,
}) => {
return (
<div>
<Checkbox
isActive={isActive}
value={id}
checked={isActive}
onChange={onChange}
/>
<Title >{name}</Title>
</div>
)
}
As far as I understand you want the tabs not to change when you click on the check box.
To do this, you can pass the onClick function to the Checkbox and stop the event bubbling there
const Header = ({ name, onChange, isActive, id }) => {
return (
<div>
<Checkbox
isActive={isActive}
value={id}
checked={isActive}
onChange={onChange}
onClick={(e) => {
e.stopPropagation();
}}
/>
<Title>{name}</Title>
</div>
);
};

Unable to make a custom radio control a part of the radio group that already contains dynamic generated radio controls

Here is a link to the code that is referenced below in my question - https://codesandbox.io/s/material-demo-forked-gtztx?file=/demo.tsx
In the code below (or demo.tsx from the codesandbox link above ), I am trying to combine a new FormControlLabel radio button (line 24) into the dynamically generated material UI radio buttons.
I don't want to add this new radio button into the "options" list within "index.tsx", but I still want this new radio button to be within the same "payment" radio group.
Current behavior: After the page renders, this custom radio with the label as Unknown always remains checked.
Expected behavior: Make this custom radio button work as a part of the dynamically created "payment" radio groups without adding it to the "options" list (see index.tsx)
export default function RadioButtonsGroup(props) {
const [value, setValue] = React.useState(null);
console.log(value);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setValue((event.target as HTMLInputElement).value);
};
return (
<FormControl component="fieldset">
<FormLabel component="legend">Payment</FormLabel>
<RadioGroup
aria-label="payment"
name="payment1"
value={value}
onChange={handleChange}
>
{/* <FormControlLabel value={value} control={<Radio />} label="Unknown" /> */}
{props.options.map(([value, readable], index) => (
<FormControlLabel
key={index}
value={value}
control={<Radio />}
label={readable}
/>
))}
</RadioGroup>
</FormControl>
);
}
This is what you need - https://codesandbox.io/s/material-demo-forked-jgopr
Basically, I added a checked prop to all the radio buttons (the custom one and the ones in the optionList) to correctly show the selected state of radio control for the value in the component state.

How can I get the onChange method to get the value of a dynamically rendered Select?

I have the following Select from Material UI:
<FormControl className='select-form'>
<InputLabel id="demo-simple-select-outlined-label">Choose User</InputLabel>
<Select
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
value={this.state.userId}
onChange={this.handleChange}
label="choose-user"
>
{Object.keys(users).map(uId => (
<div key={uId}className='select-menu'>
<img
src={''}
alt={`Avatar of me`}
className='signin-avatar'
/>
<MenuItem value={30}>{users[uId].name}</MenuItem>
</div>
))}
<MenuItem value={20}>Hello</MenuItem>
</Select>
</FormControl>
My handleChange method gets the value of the MenuItem below with the value of 20 when selected. I just used that as a test and the Select and the onChange work just fine.
The problem is the div, that get dynamically rendered from the users object. I want to render an avatar and the name of the user in every MenuItem. I have to pack them in a div, because the .map() needs to have one parent item.
I want to pass the value (the user id) of the selected MenuItem to the handleChange method, but all I get is an undefined when a user select is clicked.
How can I pass the value of the select to the onChange method, when the Select items are packed inside a div?
The correct way is to put your image inside the MenuItem, and you will get the value
{
Object.keys(users).map((uId) => (
<MenuItem value={uId}>
<img src={''} alt={`Avatar of me`} className="signin-avatar" />
{users[uId].name}
</MenuItem>
));
}

Material-ui's Menu Item not working with a Select within a redux-form Field (redux form 8.2)

I'm trying to create a select (dropdown) using Material-UI within a redux-form. There's an example for using M-UI's selects within a redux form on their website.
I'd like to do the same type of example except using Material UI's MenuItem's instead of the option tags used in the example.
It seems as though simply replacing the options with MenuItems does not work, and the MenuItems do not appear under the children for the select field. I have gotten this to work with options:
Here is the renderSelectField used to create the select component. This is working:
renderSelectField = ({ input, label, meta: { touched, error }, children, ...custom }) => (
<FormControl className={this.props.classes.formControl} error={touched && error}>
<InputLabel>{label}</InputLabel>
<Select
native
{...input}
{...custom}
>
{children}
</Select>
{this.renderFormHelper({ touched, error })}
</FormControl>
)
And here is the render:
render() {
return (
<div>
<form onSubmit={this.props.handleSubmit(this.props.submitForm)}>
<Field name={"sheetType"} component={this.renderSelectField} label={"Sheet Type"}>
<MenuItem value={"basic"} primaryText={"Basic"}>Basic</MenuItem>
<MenuItem value={"advanced"} primaryText={"Advanced"}>Advanced</MenuItem>
</Field>
<Button onClick={this.props.onCancel}>Cancel</Button>
<Button type="submit" color={"secondary"}>Next</Button>
</form>
</div>
)
}
I expect there to be two dropdown menu items passed in as the children of MenuItem, but i believe there needs to be some property passed into MenuItem itself.
Replacing menu item with option tags work.
You are mixing between simple Select and native Select. If you going to use native change <MenuItem> to <option> otherwise just remove native property.
Native pattern:
<Select native>
<option value="item">item</option>
</Select>
Simple Select pattern:
<Select>
<MenuItem value="item">item</MenuItem>
</Select>

How to set default value in material-UI select box in react?

I am using Select box from material-ui
I want to show "select the value" option by default selected but after that user is not able to select this option.
<FormControl required className={classes.formControl}>
<InputLabel htmlFor="circle">Circle</InputLabel>
<Select
value={circle}
onChange={event => handleInput(event, "circle")}
input={<Input name="circle" id="circle" />}
>
<MenuItem value="" disabled>
<em>select the value</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
<FormHelperText>Some important helper text</FormHelperText>
</FormControl>
Current code on sandbox: https://codesandbox.io/s/xoylmlj1qp
I want to make like this: https://jsfiddle.net/wc1mxdto/
Update
I changed the state 20 to blank string in circle
form: {
searchValue: "",
circle: '',
searchCriteria: ""
}
now expected output should be dropdown should show "please select value" but currently it showing this
You need to provide correct MenuItem value in state to be matched on render.
Here is the working codesandbox: Default Select Value Material-UI
You can just pass the displayEmpty into select
<Select
id="demo-simple-select-outlined"
displayEmpty
value={select}
onChange={handleChange}
>
and define the menuItem like
<MenuItem value=""><Put any default Value which you want to show></MenuItem>
As React introduced React-Hooks, you just need to pass your default value in React.useState() as React.useState(10).
export default function CustomizedSelects() {
const classes = useStyles();
const [age, setAge] = React.useState(10);// <--------------(Like this).
const handleChange = event => {
setAge(event.target.value);
};
return (
<form className={classes.root} autoComplete="off">
<FormControl className={classes.margin}>
<Select
value={age}
className={classes.inner}
onChange={handleChange}
input={<BootstrapInput name="currency" id="currency-customized-select" />}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</form>
);
}
<FormControl variant="outlined" className={classes.formControl}>
<InputLabel id="uni">UNI</InputLabel>
<Select
key={value}
defaultValue={value}
labelId="uni"
id="uni"
name="uni"
onBlur={onChange}
label="uni"
>
{unis.map((u, i) => (
<MenuItem value={u.value} key={i}>
{u.label}
</MenuItem>
))}
</Select>
</FormControl>;
Just use the defaultValue attribute of select.
You can refer to the Material UI Select API Docs to know more.
import React from 'react';
import {useState} from 'react';
import FormControl from '#material-ui/core/FormControl';
import InputLabel from '#material-ui/core/InputLabel';
import Select from '#material-ui/core/Select';
import MenuItem from '#material-ui/core/MenuItem';
const Selector = () => {
const [Value, setValue] = useState("1"); // "1" is the default value in this scenario. Replace it with the default value that suits your needs.
const handleValueChange = event => {
setValue(event.target.value);
}
return(
<FormControl>
<InputLabel id="Input label">Select</InputLabel>
<Select
labelId= "Input label"
id= "Select"
value= {Value}
defaultValue= {Value}
onChange= {handleValueChange}
>
<MenuItem value="1">Item1</MenuItem>
<MenuItem value="2">Item2</MenuItem>
<MenuItem value="3">Item3</MenuItem>
</Select>
</FormControl>
)
};
export default Selector;
If you take a look at the Select Api of Material UI here, you could do it easily.
As explained above, you need to pass the default value in your state variable:
const [age, setAge] = React.useState(10);// <--------------(Like this).
Set displayEmpty to true:
If true, a value is displayed even if no items are selected.
In order to display a meaningful value, a function should be passed to the renderValue prop which returns the value to be displayed when no items are selected. You can only use it when the native prop is false (default).
<Select
displayEmpty
/>
I had a similar issue. In my case, I applied a function directly to onChange so I had something like this:
export default function CustomizedSelects() {
const classes = useStyles();
const [age, setAge] = React.useState(10);
return (
<form className={classes.root} autoComplete="off">
<FormControl className={classes.margin}>
<Select
value={age}
className={classes.inner}
onChange={(event) => setAge(event.target.value)}
input={<BootstrapInput name="currency" id="currency-customized-select" />}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</form>
);
}
I also had a separate button to clear select value (or select the default empty value). All was working, the select value was set correctly, except the Select component did not animate to its default form - when no value is selected. I fixed the problem by moving onChange to a handleChange separate function as it is in the code example #B4BIPIN is presenting.
I am not an expert in React and still learning and this was a good lesson. I hope this helps ;-)
Take a list of objects you want to display in the Select dropdown and initialise it using useState. Use the state now to show the value and update the state on the change of the dropdown.
const ackList = [
{
key: 0,
value: "Not acknowledged",
},
{
key: 1,
value: "Acknowledged",
},
];
function AcknowledgementList() {
//state to initialise the first from the list
const [acknowledge, setAcknowledge] = useState(ackList[1]);
//update the state's value on change
const handleChange2 = (event) => {
setAcknowledge(ackList[event.target.value]);
};
return (
<TextField
select
fullWidth
value={acknowledge.key}
onChange={handleChange2}
variant="outlined"
>
{ackList.map((ack) => (
<MenuItem key={ack.key} value={ack.key}>
{ack.value}
</MenuItem>
))}
</TextField>
);
}
The problem here is all to do with some pretty poor coding on the part of the MUI folks, where on several components, they have magic strings and really are doing silly things.
Let's take a look at the state here:
const [age, setAge] = React.useState('3');
You can see that we are having to specify the VALUE as a string. Indeed the data type that the Select control takes is a string | undefined. So the fact we are having to use a number value as a string is the source of confusion.
So how does that work?
It is all to do with the MenuItem component. Let's take a look:
<MenuItem value={1}>First Choice</MenuItem>
<MenuItem value={2}>Second Choice</MenuItem>
<MenuItem value={3}>Third Choice</MenuItem>
You can see that we are indeed having to specify the VALUE of the MenuItem as a number.
So in this case, specifying '3' as the State value, as a string, will select the Third Choice on load.
You can set the VALUE in the Select control as the state value.
Don't forget, when handling the onChange event, that you will need to convert the event.target.value to string.

Resources