Close dropdown in React JS - reactjs

<select open={false} autoFocus={true} onClick={this.handleClick} size={5}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
I have made a dropdown, but I cannot close it. I do not want close it with display:none

You can initially show 5 items and, after selecting close it(set to 1 using a state)
import React, { useState } from "react";
function App() {
const [defaultSize, setDefaultSize] = useState(5);
const handleClick = () => {
setDefaultSize(1);
// do other stuff
}
return (
<div>
<select open={false} autoFocus={true} onClick={handleClick} size={defaultSize}>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</div>
);
}
export default App;

Remove the size attribute. change onClick to onChange add value attribute for select tag
<select value={myCar} onChange={handleChange}>

Related

Add a disabled default option to select

I want to have a default option in select saying "Select your option". But I want in to be disabled, which means that user should not be able to select it once he choose any value.
Here is an example:
function Select() {
const [option, setOption] = useState();
function handleOnChange(event) {
setOption(event.target.value);
}
return (
<select value={option} onChange={handleOnChange}>
<option disabled>Select your option</option>
{OPTIONS.map(value => (
<option key={value} value={value}>{value}</option>
))}
</select>
);
}
But if I'm adding a disabled prop to option it selects the first option which is not disabled. What should be adjusted to make it work?
Thanks in advance
what you need to do is to provide a default value to your useState and a value for your default option, so it gets selected. Like this:
function Select() {
const [option, setOption] = useState('');
function handleOnChange(event) {
setOption(event.target.value);
}
return (
<select value={option} onChange={handleOnChange}>
<option value='' disabled>Select your option</option>
{OPTIONS.map(value => (
<option key={value} value={value}>{value}</option>
))}
</select>
);
}

Search only with text ignoring emoji in antd Select component

I have select component of antd where option label is not text. Option label has text along with emoji. Now If user want to search for particular text, the select component is not able to search the text which has emojis.
What I want to have is User should search a particular text ignoring the emoji.
import React from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Select } from 'antd';
const { Option } = Select;
const App = () => (
<Select
showSearch
style={{
width: 200,
}}
placeholder="Search to Select"
optionFilterProp="children"
filterOption={(input, option) => option.children.includes(input)}
>
<Option value="1"><span>😁</span> Not Identified</Option>
<Option value="2"><span>🙄</span> Closed</Option>
<Option value="3"><span>😪</span> Communicated</Option>
<Option value="4"><span>😚</span> Identified</Option>
<Option value="5"><span>🥱</span> Resolved</Option>
<Option value="6"><span>😫</span> Cancelled</Option>
</Select>
);
export default App;
If need, I have a codesandbox link.
here just use toLowerCase() string function it's work i just updated pls check here codesandbox link
import React from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Select } from "antd";
const { Option } = Select;
const onHandleSearch = (input, option) => {
let optionChildren = option.children.filter(
(item) => typeof item === "string"
);
return optionChildren[0].toLowerCase().includes(input.toLowerCase());
};
const App = () => (
<Select
showSearch
style={{
width: 200
}}
placeholder="Search to Select"
optionFilterProp="children"
filterOption={(input, option) => onHandleSearch(input, option)}
>
<Option value="1">
<span>😁</span> Not Identified
</Option>
<Option value="2">
<span>🙄</span> Closed
</Option>
<Option value="3">
<span>😪</span> Communicated
</Option>
<Option value="4">
<span>😚</span> Identified
</Option>
<Option value="5">
<span>🥱</span> Resolved
</Option>
<Option value="6">
<span>😫</span> Cancelled
</Option>
</Select>
);
export default App;

How can you an the values of a selector into an empty string?

I have a selector in where I take the month, year and day of birth of a person in order to register him/her in the platform. I've tried to implement a loop to get the text content of the selector. After debugging I realized that the month for example always gets replaced by the last value, no matter what I put. For example if I choose March, It change the monthOfBirth to December no matter what.
import React, {useState} from 'react'
import './signup.css'
import axios from 'axios'
function Signup() {
const [useEmail, setUseEmail] = useState(true)
const [username, setUsername] = useState('')
const [email, setEmail] = useState('')
const [phone, setPhone] = useState('')
const [password, setPassword] = useState('')
const [monthOfBirth, setMonthOfBirth] = useState('')
const toggleEmail = () => {
if(useEmail) {
setUseEmail(false)
} else {
setUseEmail(true)
}
}
const onChangeUsername = (e) => {
setUsername(e.target.value)
}
const successAlert = () => {
alert("successful")
}
const onChangeEmail = (e) => {
if(useEmail) {
setEmail(e.target.value)
} else {
setPhone(e.target.value)
}
}
const onPasswordChange = (e) => {
setPassword(e.target.value)
}
const onSubmit = (e) => {
e.preventDefault()
const users = {
username: username,
email: email,
phone: phone,
password: password,
}
axios.post('http://localhost:5000/users/add', users)
.then(res => console.log(res.data))
}
const getValues = (e) => {
for (var i = 0; i < e.target.length; i++) {
setMonthOfBirth(e.target[i].textContent)
console.log(monthOfBirth)
}
}
const getYears=(start,end)=>{
let _years=[]
for(let i=start;i<=end;i++){
_years.push(i)
}
return _years
}
let years = getYears(1901,2021)
return (
<div className="modalsignup">
<div className="modal____popupform">
<img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-logo-vector-png-clipart-1.png" className="twitterLogo____signup" />
<form onSubmit={onSubmit}>
<h1 className="signup_____headertext">Create your account</h1>
<input placeholder="Name" onChange={onChangeUsername} className="placeholder____divcreateaccount"/>
{useEmail ? <input placeholder="Email" onChange={onChangeEmail} className="placeholder____divcreateaccount" />: <input placeholder="Phone" onChange={onChangeEmail} className="placeholder____divcreateaccount"/>}
<div>
<button className="switcher_____button" onClick={toggleEmail}>Use {useEmail ? "phone" : "email"} instead</button>
</div>
<input placeholder="Password" onChange={onPasswordChange} className="placeholder____divcreateaccount" type="password"/>
<div>
<h4 className="birthdate____signup">Date of birth</h4>
<p className="birthdate______paragraph">This will not be shown publicly. Confirm your own age, even if this account is for a business, a pet, or something else.</p>
</div>
<div className="selector_____options">
<div>
<select onClick={getValues} className="selector_____months">
<option value="0">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</div>
<div>
<select className="selector_______days">
<option value="0">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
</div>
<div>
<select className="selector______year">
<option>Year</option>
{years.map(get => {
return <option value={get} key={get}>{get}</option>
})}
</select>
</div>
</div>
<div>
<button className="signup_____button" onClick={successAlert}>Next</button>
</div>
</form>
</div>
</div>
)
}
export default Signup
You have some problems in your code:
You should change onClick in the select option to onChange.
Using console.log(monthOfBirth) after setMonthOfBirth(label) in getValues method is not give the correct state, because the setMonthOfBirth which created from useState hook is an async method. When it's running you can't see the actual new state in the console. For getting the correct state after setMonthOfBirth You need a callback function.
Loop through the e.target.length for getting the selected value is not correct.
You can change getValues to bellow for getting the correct result:
const getValues = (e) => {
let index = e.nativeEvent.target.selectedIndex;
let label = e.nativeEvent.target[index].text;// getting text of the month for example : December,November...
let value = e.target.value;// getting value of the month : 11,12,...
setMonthOfBirth(label);
};
Also change the select to:
<select onChange={getValues} className="selector_____months">
And for seeing the correct state you can use use-state-with-callback and define your state same as bellow:
const [monthOfBirth, setMonthOfBirth] = useStateWithCallback("", () => {
console.log(monthOfBirth);
});

How to send back a parameter to a function pass as a param in react

I am new to react.js and find it difficult to understand the parent child component communication.
I have a Stateful component, call cookpit and a Stateless component call Schedule. I am passing a change function to Schedule from cookpit as props.
state = {
schedule : [
{
id:'01',
shift:"Morning UpStairs",
Monday:'X1',
Tuesday:'',
Wednesday:'',
Thursday:'',
Friday:''
},
{
id:'02',
shift:"Morning Down Stairs",
Monday:'X2',
Tuesday:'',
Wednesday:'',
Thursday:'',
Friday:''
},
{
id:'03',
shift:"Morning Parking Lot",
Monday:'',
Tuesday:'',
Wednesday:'',
Thursday:'',
Friday:''
},
],
};
let mapSchedule = this.state.schedule.map((item,i)=>{
return <Schedule schedule={item} key={item.id} changed={(event,day)=>this.onEmpChanged(event,item.id,day)}/>
});
In Schedule component I want set values to the each day of the state object.
<Col>
<select value={props.schedule.Monday} onChange={props.changed('monday')}>
<option value=""></option>
<option value="X1">X1</option>
<option value="X2">X2</option>
<option value="X3">X3</option>
<option value="X4">X4</option>
<option value="X5">X5</option>
<option value="X6">X6</option>
<option value="X7">X7</option>
</select>
</Col>
I am trying to pass the day to the parent with the change action so that I know which date should be updated , but its not working. please correct me.
in the Parent component
changed = (day,item)=>{
console.log(item.id,day)
}
render() {
return(
<div>
{
this.state.schedule.map(item=> <Schedule schedule={item} key={item.id} changed={this.changed}/>
)
}
</div>
)
}
and in the child component
export default function Schedule(props) {
return (
<div>
<select value={props.schedule.Monday} onChange={()=>props.changed('monday',props.schedule)}>
<option value=""></option>
<option value="X1">X1</option>
<option value="X2">X2</option>
<option value="X3">X3</option>
<option value="X4">X4</option>
<option value="X5">X5</option>
<option value="X6">X6</option>
<option value="X7">X7</option>
</select>
</div>
)
}

Ant design - How do i auto close select ("tags" or "multiple" mode) dropdown after each selection?

I'm using ant.design select component ("tags" or "multiple" mode) in a page, i want dropdown to be automatically closes after each selection. Now it remains open and i should click on other places in the page to close the dropdown list.
import { Select } from 'antd';
const { Option } = Select;
function handleChange(value) {
console.log(`selected ${value}`);
}
ReactDOM.render(
<Select mode="multiple" placeholder="Select Countries" size="large" onChange={handleChange}>
<Option value="country1">Country1</Option>
<Option value="country2">Country2</Option>
<Option value="country3">Country3</Option>
<Option value="country4">Country4</Option>
<Option value="country5">Country5</Option>
<Option value="country6">Country6</Option>
</Select>,
mountNode,
);
Simply change first "Select" component to this:
<Select
mode="multiple"
placeholder="Select Countries"
size="large"
ref={(select) => this.countrySelect = select}
onChange={()=>{
this.countrySelect.blur()
}}>
<Option value="country1">Country1</Option>
<Option value="country2">Country2</Option>
<Option value="country3">Country3</Option>
<Option value="country4">Country4</Option>
<Option value="country5">Country5</Option>
<Option value="country6">Country6</Option>
</Select>
From the docs:
import { Select } from 'antd';
const Option = Select.Option;
function handleChange( value ) {
console.log( `selected ${value}` );
}
<Select defaultValue="lucy" style={ { width: 120 } } onChange={ handleChange }>
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="disabled" disabled>Disabled</Option>
<Option value="Yiminghe">yiminghe</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } disabled>
<Option value="lucy">Lucy</Option>
</Select>
<Select defaultValue="lucy" style={ { width: 120 } } loading>
<Option value="lucy">Lucy</Option>
</Select>
Use it's own <Option>
More info: https://ant.design/components/select/
import React, { useState } from 'react'
import { Select } from 'antd'
const Option = Select.Option
const SelectComponent = () => {
const [open, setOpen] = useState('')
const handleChange = value => {
console.log(`selected ${value}`)
}
return (
<Select
showSearch
mode={'multiple'}
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
open={open}
onChange={value => {
handleChange.bind(this, value)
this.setState({ open: false })
}}
onFocus={() => setOpen(true)}
onBlur={() => setOpen(false)}
onSearch={() => setOpen(true)}
>
<Option value="jack">Jack</Option>
<Option value="lucy">Lucy</Option>
<Option value="tom">Tom</Option>
</Select>
)
}
export default SelectComponent

Resources