antd select option with search functionality - javascript

i dont know if this is possible but at the moment when user click from select options it will take to that specific url, my point is can we have search functionality in 'Search...' so user could search from hundreds of option and then choose it and click the button and that button should also take to that same 'onChange' address. You can also suggest other options, even without select but functionality must be same , here is my code:
import "antd/dist/antd.css";
import { Select } from "antd";
// import { Link, useHistory, useRouteMatch, useParams } from "react-router-dom";
function EventsSection() {
// const history = useHistory();
const { Option } = Select;
// const changeHandler = (id) => {
// history.push(`/customer/${id}`);
// };
return (
<div>
{/* when found in search i want this button take to 'onChange' address also*/}
<button>click me when found in search</button>
<Select
style={{ width: 200 }}
placeholder="Search..."
mode="multiple"
open={true}
listHeight={128}
// onChange={changeHandler}
>
<Option value="1">Not Identified</Option>
<Option value="2">Closed</Option>
<Option value="3">Communicated</Option>
<Option value="4">Identified</Option>
<Option value="5">Resolved</Option>
<Option value="6">Cancelled</Option>
</Select>
</div>
);
}
export default EventsSection;

The first part is done.
Check at CodeSanbox.
The second part is still unclear to me.
Exactly this part
and then that button can be cliked which should take user to that
’onChange’

Related

I need to clear values of datePicker when selecting item of selection box in react js

const startDateRef = useRef();
const dateFilter = (event) => {
startDateRef.current.value = "";
}
<Form.Group controlId="dob" ref={startDateRef}>
<Form.Label>Start Date</Form.Label>
<Form.Control
ref={startDateRef}
type="date"
name="stDate"
value={dateBetweenState.stDate}
placeholder="Date of Birth"
onChange={(e) => {
handleChange(e);
}}
/>
<select
type="text"
className="form-select"
name="stDate"
onChange={(e) => {
dateFilter(e.target.value);
}}
>
<option value={0}>Choose...</option>
<option value={7}>7 Days</option>
<option value={14}>14 Days</option>
<option value={30}>30 Days</option>
</select>
...
This is my code segment. I just typed here relevant code only. actual code too long . Anyway here have date-picker and select-box . If picked date and then select item from selection box. I need to clear early picked data from data-picker . I just tried it from react ref . I did that from when select item onChange function work and it contains the ref assigns the value to clear. but it does not work.
did you try adding the value parameter in the tag?
or
are you trying to say this,
you are trying to clear the value of the date picker, in terms of actual data in the useRef is updated but this is not being reflected on the UI?
if so then there is a simple trick that I use for updating the UI forcefully
try these method if it works:
remounting using useState and refreshing logic
const [refreshing, setRefreshing] = useState(false);
useEffect(() => {
if(!!refreshing) {
setRefreshing(false);
}
}, [refreshing])
// this will update the state to refreshing as true and the above useEffect will immediately update the state to false
const refresh = () => {
setRefreshing(true)
}
...
{!refreshing && <select
...
onChange={(e) => {
dateFilter(e.target.value);
}}
>
...
</select>}

How to capture when dropdown is open on React

Is there a way to tell when the dropdown is open and also closed? onfocus and onblur doesn't seem to be working.
<div className="select-container">
<select>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</div
You should use useState to keep track of the dropdown status. It would look something like this:
import "./styles.css";
import { useState } from "react";
export default function App() {
const [isDropDownOpen, setDropDownOpen] = useState(false);
let options = [
{
label: "money"
}
];
const handleSelect = () => {
setDropDownOpen(!isDropDownOpen);
};
const handleBlur = () => {
setDropDownOpen(!isDropDownOpen);
};
console.log(isDropDownOpen);
return (
<div>
<select onBlur={handleBlur} onClick={handleSelect}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</div>
);
}
I have tied it into the handleSelect function, which will probably do more than just keep track of whether or not the dropdown is open but either way, it works as a reference point for now.
EDIT: Also, in case you click outside the dropdown, I used onBlur, which is controlled by handleBlur to change the boolean value because obviously, the dropdown will close.
Check the console.log on the this code sandbox to see how it works: https://codesandbox.io/s/amazing-easley-0mf7o3?file=/src/App.js

Select Dropdown not Passing Selected Values to Array in React

I am building a dropdown menu in React using a select dropdown.
or some reason, my selected value is not passing, it is passing the entire array instead of the value I selected on the dropdown.
What am I doing wrong here and how can I pass the value that I selected via dropdown?
Dropdown Code in React
<select
className='add-cap-select'
onChange={(value) => handleChangeForm('agent', value)}
>
{agents.map((agent) => (
<option id='agent' key={agent} value={form.agent}>
{agent}
</option>
))}
</select>
/**
* Handles when the user changes any regular form entry
* #param {String} prop
* #param {String} value
*/
const handleChangeForm = (prop, value) => {
setForm({
...form,
[prop]: value
})
}
Here is my simple solution to do this
import React, {useState} from 'react';
export function App(props) {
const [agent, setAgent] = useState({
agent:'',
});
const handleChangeForm = event =>{
console.log(event.target.name, event.target.value)
setAgent({...agent,[event.target.name]:event.target.value})
}
return (
<select
className='add-cap-select'
name="agent"
onChange={(event) => handleChangeForm(event)}
>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
);
}
you are passing agent and value both in handleFormChange, instead of this you can put the name in select, and from the event, you can get the name as well as value, here you are directly passing value which is event actually if you want to do in your solution then you can do like this -> value.target.value

REACT: Undesirable arrows inside html <select>

SOLUTION: as #prasanth sugested me, I created a fake dropdown, a placeholder.
Both the fake and the real dropdown shares a
style={{"display":countryChange?"":"none"}}
obviously the real one is inverted with the fake one. Once i ping the api, I hide the real one and show the fake one. Once the api returns with value, i write the state so the fake disapears. Worked like a charm.
I'm new to react, and trying to make a dynamic dropdown based on an api call. I have a local api in "/avaliable_countries" which returns {countries:"Brasil" and "United States"}. I want those two fields to create the <options> dynamcially, and it is almost working as intended.
The problemis: In the first click, I got this weird arrows. If I click out/again or two times, then it becomes normal.
no click:
first click, weird arrows(and using the weird arrows can navigate between the two countries):
Clicking in/out or two times in a row, becomes the desired output:
Without any CSS(weird arrows still here):
The code:
import React,{useState} from 'react';
import {Link} from 'react-router-dom';
import './styles.css';
import api from '../../services/api';
export default function Signup(){
var [countriesObj, setCountriesObj] = useState(<option>Select your country</option>)
async function getAvaliableCountries(){
setCountriesObj();
try{
const response = await api.get(
'avaliable_countries','',
{headers: {
'Content-Type':"application/json",
}
});
window.arrayOfCountries = response.data.countries ;
let countriesList = (window.arrayOfCountries.map((data) =>
<option>
{data}
</option>)
);
setCountriesObj(countriesList);
}catch(err){
alert('Error obtaining the list of countries.')
}
}
return(
<div className="wrapper">
<div id="formContent">
<h2 className="inactive underlineHover">
<Link to="/">Sign In</Link>
</h2>
<h2 className="active">
Sign Up
</h2>
<form>
<select
onClick={getAvaliableCountries}
name="animal"
className="form-control">
{countriesObj}
</select>
</form>
<div id="formFooter">
</div>
</div>
</div>
);
}
You could do like this .Component use with in array not a good practise.so extract the component with Array#map on render .And dont forget use the key on map child options
Updated :
load the array on component mount instead of click . try this useEffect with in react
Demo code
import React,{useState,useEffect} from 'react';
import {Link} from 'react-router-dom';
import './styles.css';
import api from '../../services/api';
export default function Signup() {
var [countriesObj, setCountriesObj] = useState(['select'])
async function getAvaliableCountries() {
setCountriesObj();
try {
const response = await api.get(
'avaliable_countries', '', {
headers: {
'Content-Type': "application/json"
}
}
);
window.arrayOfCountries = response.data.countries;
let countriesList = response.data.countries
setCountriesObj(countriesList);
} catch (err) {
alert('Error obtaining the list of countries.')
}
}
useEffect(()=>{
getAvaliableCountries()
},[])
return(
<div className="wrapper">
<div id="formContent">
<h2 className="inactive underlineHover">
<Link to="/">Sign In</Link>
</h2>
<h2 className="active">
Sign Up
</h2>
<form>
<select name="animal" className="form-control">
{countriesObj.map(data => (
<option key={data}>{data}</option>
))}
</select>
</form>
<div id="formFooter">
</div>
</div>
</div>
);
}
This is actually not React related and you can use simple CSS to remove the arrow:
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none; /* Remove default arrow */
background-image: url(...); /* Add custom arrow */
}
For more information you can see the original answer here: How do I style a dropdown with only CSS?
Kindly check your css and there must some css like "content: '<>';" which is crreating issue for this type of style.
It's not because of react and it's css issue so kindly check css (style.css) of select.

Can't get selected value from dropdown

I have a form that contains an input and a dropdown that's filled with elements from an API. But I'm having a probem, whenever I submit the form It only passes the value from the input and not the dropdown.
It's weird because when I click inspect element on the form it show that each option has a value and a label.
My code is simple, I have a form that has an input and a dropdown, I get an int from the input and a value from the dropdown and it creates an element via POST request, but that happens in the background since I only pass the parameters here.
I am using the Redux Form library for my form controls
here's my code:
import React from 'react';
import {reduxForm, Field} from 'redux-form';
import {Input} from 'reactstrap';
import {connect} from 'react-redux';
import { renderField } from '../form';
import {ticketAdd} from "../actions/actions";
import {Message} from "./Message";
const mapDispatchToProps = {
ticketAdd
};
class AmendeForm extends React.Component {
onSubmit(values) {
const { ticketAdd, parkingId } = this.props;
return ticketAdd(parseInt(values.matricule),parkingId,parseInt(values.montant));
}
render() {
const { handleSubmit, submitting, voitureList } = this.props;
console.log(voitureList);
if (null === voitureList) {
return (<Message message="Pas de voitures"/>);
}
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Input type="select" name="matricule" id="exampleSelect" label="Matricule">
{
voitureList.map(voiture => {
return (
<option value={voiture.id} key={voiture.id}>{voiture.matricule}</option>
);
})
}
</Input>
<Field name="montant" type="number" label="Montant" component={renderField}/>
<button type="submit" className="btn btn-primary btn-big btn-block" disabled={submitting}>Ajouter ticket</button>
</form>
)
}
}
export default reduxForm({
form: 'AmendeForm'
})(connect(null, mapDispatchToProps)(AmendeForm))
It's because your dropdown form field isn't wrapped by redux-form <Field /> component.
You have to create a custom dropdown Component (let's name it <Dropdown />) and later pass it to the Field as follows:
<Field name='matricule' component={Dropdown} />
Keep in mind that in your <Dropdown /> component, you have to adapt the props passed down by <Field /> with your custom Dropdown props. For example, <Field /> will pass down input prop, which includes itself onChange, onBlur and other handlers, these should be passed down to your custom Dropdown too.
Here's a basic example how to create such a custom Dropdown component:
const Dropdown = ({ input, label, options }) => (
<div>
<label htmlFor={label}>{label}</label>
<select {...input}>
<option>Select</option>
{ options.map( o => (
<option key={o.id} value={o.id}>{o.label}</option>
)
)}
</select>
</div>
)
Usage
const options = [
{ id: 1, label: 'Example label 1' },
{ id: 2, label: 'Example label 2' }
]
<Field name='marticule' component={Dropdown} options={options} />
For advanced use-cases, please refer to the docs.
Also, you're using reactstrap, and here's a discussion of how to create such custom Dropdown component, which is adapted with redux-form.

Categories

Resources