I have two Select input to display data. lets say 1 Select is for product and other for display product list based on selected product in select 1. But i had an error that react didnt display my view. after i command the second Select it is run normally.
this is my Select input to select product and coverage:
<div>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
{TOC.map((type, index) => (
<Select.Option key={type.id} value={type.id}>
{type.desc}
</Select.Option>
))}
</Select>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
{Coverage.map((type, index) => (
<Select.Option key={type.id} value={type.id}>
{type.desc}
</Select.Option>
))}
</Select>
</div>
i get the coverage data by hit the api, after select product using hooks state
Like this:
const getCoverage = () => {
axios.post( url, data, headers).then(function (response){
if(response.data.Data == 'success') {
setCoverage(response.data.Data)
}
})
}
const handleChangeSelect = (e) => {
setTocId(e);
console.log(TocId);
getCoverage();
};
Hard to tell without seeing the rest of your code but are you fetching Coverage for the first time in handleChangeSelect?
If so, that would be the issue since Coverage doesn't exist in your first render.
A potential workaround could be to make the Coverage options render conditionally.
<div>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
{TOC.map((type, index) => (
<Select.Option key={type.id} value={type.id}>
{type.desc}
</Select.Option>
))}
</Select>
<Select onChange={handleChangeSelect} value={TocId} name="ProductID" size="sm">
{Coverage && Coverage.length > 0 && Coverage.map((type, index) => (
<Select.Option key={type.id} value={type.id}>
{type.desc}
</Select.Option>
))}
</Select>
</div>
It looks fine. As per my perception, it's an issue of empty state rendering. Render your component conditionally. Also, put a different name prop.
<div>
<Select
onChange={handleChangeSelect}
value={TocId}
name="ProductID"
size="sm"
>
{TOC?.map((type, index) => (
<Select.Option key={type.id} value={type.id}>
{type.desc}
</Select.Option>
))}
</Select>
<Select
onChange={handleChangeSelect}
value={TocId}
name="ProductID"
size="sm"
>
{Coverage?.map((type, index) => (
<Select.Option key={type.id} value={type.id}>
{type.desc}
</Select.Option>
))}
</Select>
I'm working on react and I have several drop-down and text fields where I want to clear/reset selected values from the select options and from the text field when I click the clear button. I've tried some logic, but it doesn't work. can someone help me? I created a function called "handleReset" but it does nothing and doesn't show an error.
Here is my code:
import React, { useState, useEffect } from "react";
import {
Button,
Container,
} from "react-bootstrap";
import { CarAction } from "../../Store/Actions/CarAction";
import { useDispatch, useSelector } from "react-redux";
const CarRequests = () => {
const dispatch = useDispatch();
const getCarMake = useSelector((state) => state.CarReducer.car);
const getCarMileage = useSelector((state) => state.CarReducer.mileage);
const getCarTrim = useSelector((state) => state.CarReducer.trim);
let [value, setValue] = useState()
let handleChange = (e) => {
setValue(e.target.value)
}
const handleReset = (e) => {
setValue(e.target.value = "");
}
useEffect(() => {
dispatch(CarAction.CarMake());
dispatch(CarAction.CarMileage());
dispatch(CarAction.CarTrim());
}, [dispatch]);
return (
<div className="flex-row align-items-center section">
<h3>
Filters
<i className="fa fa-cog icon float-right"></i>
</h3>
<Container className="box-shadow p-4">
<div className="form-row">
<div className="form-group col-lg-3">
<label>Make:</label>
<select className="custom-select" onChange={handleChange}>
<option value=''>Please select...</option>
{getCarMake.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}
</select>
</div>
<div className="form-group col-md-3">
<label>Model:</label>
<select className="custom-select">
<option value=''>Please select...</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div className="form-group col-md-3">
<label>Year:</label>
<select className="custom-select">
<option value=''>Please select...</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div className="form-group col-md-3">
<label>Mileage:</label>
<select className="custom-select" onChange={handleChange}>
<option value=''>Please select...</option>
{getCarMileage.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}
</select>
</div>
</div>
<div className="form-row">
<div className="form-group col-md-3">
<label>Car Trim:</label>
<select className="custom-select" onChange={handleChange}>
<option value=''>Please select...</option>
{getCarTrim.map((data, key) => <option value={data.value} key={key}>{data.name}</option>)}
</select>
</div>
<div className="form-group col-md-3">
<label>Email:</label>
<input type="email" placeholder="Email" className="custom-select" />
</div>
<div className="form-group col-md-3">
<label>Phone no:</label>
<input type="number" placeholder="Phone no" className="custom-select" />
</div>
</div>
<div className="container-buttons">
<Button className="mr-4" variant="light">
Search
</Button>
<Button variant="dark" onClick={handleReset}>Clear</Button>
</div>
</Container>
</div>
);
};
export default CarRequests;
The thing you are doing wrong is in handleReset function you are taking the event and you are setting the target value to empty which is ideally wrong.
In order to correct it we need to understand how the flow is working, you are using handleChange function in order to set the values to your state.
So in order to reset it you need to reset the value of the state only.
So the code becomes like this:
const handleReset = () => {
setValue("");
}
Now this will reset the value of your state variable and also use your state variable in your select method which will resolve the problem.
<select value={value}>
<option></option>
.
.
</select>
To make dynamic field working:
function App() {
const [value, setValue] = useState({});
const arr = ["hello", "cra"];
const arr2 = [
{
name: "hello",
id: "1",
},
{
name: "test2",
id: "2",
},
];
const handleChange = ({ target: { value: val, name } }) => {
setValue({ ...value, [name]: val });
};
const resetValue = () => {
setValue({});
};
console.log(value);
return (
<div id="wrapper">
<select
name="select1"
value={value.select1 || ""}
onChange={handleChange}
>
<option value=""></option>
{arr.map((val) => {
return <option value={val}>{val}</option>;
})}
</select>
<select
name="select2"
value={value.select2 || ""}
onChange={handleChange}
>
<option value=""></option>
{arr2.map(({ name, id }) => {
return <option value={id}>{name}</option>;
})}
</select>
<button onClick={resetValue}>Reset</button>
</div>
);
}
Or else you can initialise the value in your state as well like this
const [value, setValue] = useState({select1: "" , select2: ""});
which could further be used dynamically in your select tag for name attributes.
function App() {
const [value, setValue] = useState({ select1: "", select2: "" });
const arr = ["hello", "cra"];
const arr2 = [
{
name: "hello",
id: "1",
},
{
name: "test2",
id: "2",
},
];
const handleChange = ({ target: { value: val, name } }) => {
setValue({ ...value, [name]: val });
};
const resetValue = () => {
setValue({
select1: "",
select2: "",
});
};
console.log(value);
return (
<div id="wrapper">
<select name="select1" value={value.select1} onChange={handleChange}>
<option value=""></option>
{arr.map((val) => {
return <option value={val}>{val}</option>;
})}
</select>
<select name="select2" value={value.select2} onChange={handleChange}>
<option value=""></option>
{arr2.map(({ name, id }) => {
return <option value={id}>{name}</option>;
})}
</select>
<button onClick={resetValue}>Reset</button>
</div>
);
}
Seems you are trying to store multiple values in the value . don't use the word value there. I have tried to change it to [formValue, setFormValue]
Change 1:
let [formValue, setFormValue] = useState({
textfield1: '',
dropdownfield2: ''});
Change 2 - for dropdown changed values:
const handlDropDownChange = (event, value) => {
setFormValue({
...formValue,
['dropdownfield2']: value,
});
}
Change 3 - for mapping dropdown values from state, also use this to map to dropdown value:
formValue.dropdownfield2
Change 4 - for text field changes:
onChange={e => {
updateFieldMyForm(e);
}}
const updateFieldMyForm= e => {
setFormValue({
...formValue,
[e.target.name]: e.target.value
});
};
Note this will work for all text fields - just make sure that the name of this textfield matches the name used in the useState statement like - textfield1
Change 5 - to reset the whole thing at the end/submission
EDIT - 1
const handleReset = () => { setFormValue({ textfield1: "", dropdownfield2: "" }); };
Spread operator is the key in steps 2 & 4 [triple dots - ...] - let me know if you still have challenges.
I have created a 3 select option inputs based on 1st selection option it should populate the 2nd dropdown and based on 1st and 2nd selected option then it should populate the 3rd dropdown.
Unexpected token
const availableState = data.countries.find((c) => c.name === selectedCountry);
const availableCities = availableState?.states?.find((s) => s.name === selectedState);
render method select options
<div>
<label>Country</label>
<select
placeholder="Country"
value={selectedCountry}
onChange={(e) => setSelectedCountry(e.target.value)}
>
<option>--Choose Country--</option>
{data.countries.map((value, key) => {
return (
<option value={value.name} key={key}>
{value.name}
</option>
);
})}
</select>
</div>
<div>
<label>State</label>
<select
placeholder="State"
value={selectedState}
onChange={(e) => setSelectedState(e.target.value)}
>
<option>--Choose State--</option>
{availableState?.states.map((e, key) => {
return (
<option value={e.name} key={key}>
{e.name}
</option>
);
})}
</select>
</div>
<div>
<label>City</label>
<select
placeholder="City"
value={selectedCity}
onChange={(e) => setSelectedCity(e.target.value)}
>
<option>--Choose City--</option>
{availableCities?.cities.map((e, key) => {
return (
<option value={e.name} key={key}>
{e}
</option>
);
})}
</select>
</div>
I would to display multiple items in a select dropdown.
This is the code. But what i get back are many selects, one for each item i wanted to display in the dropdown.
mostraReferti(id) {
axios.get('http://localhost:8080/api/REFERTOs/' + id)
.then(response => {
this.setState({ referti: response.data }, () => {
console.log("response.data")
console.log("THIS.STATE", this.state);
})
})
.catch(err => console.log(err))
}
render() {
const refertiItems = this.state.referti.map((referti, i) => {
return (
<RefertiItems key={referti.hash_referto} item={referti} />
)
})
<Form>
<Label for="type" text="Referto" />
<div className="custom-select">
{refertiItems}
</div>
</Form>
And RefertiItems is :
render(){
console.log("SONO DENTRO")
return (
<div className={styles}>
<div className= "custom-select">
<Label for="type" text="Codice Referto" />
<select
name="codiceReferto"
placeholder="Selezionare Referto"
onKeyPress={this.onEnter} //allows you to move to the next panel with the enter key
value={this.codiceReferto}
onChange={this.handleInputChange}>
<option default value="vuoto"></option>
<option>{this.state.item.tipo_esame}-
{this.state.item.data_esame}</option>
</select>
</div>
</div>
What am i doing wrong?
First of all you have an issue with formatting. It is really difficult to understand something from code with wrong indents.
To fix your main issue you don't need to repeat your select component, just repeat options and pass it inside your select component, for example:
render() {
return (
<Form>
<Label for="type" text="Referto" />
<div className="custom-select">
<RefertiItems items={refertiItems} />
</div>
</Form>
);
}
RefertiItems:
render() {
const refertiItems = this.props.items.map((referti, i) => {
return (
<option key={referti.hash_referto}>
{referti.tipo_esame}-{referti.data_esame}
</option>
)
});
return (
<div className={styles}>
<div className= "custom-select">
<Label for="type" text="Codice Referto" />
<select
name="codiceReferto"
placeholder="Selezionare Referto"
onKeyPress={this.onEnter}
value={this.codiceReferto}
onChange={this.handleInputChange}
>
<option default value="vuoto"></option>
{refertiItems}
</select>
</div>
</div>
)
}
I have a problem here. I have an react api and i want to make a select box to filter data by specific attribute.
constructor() {
super();
this.state = {
results: []
};
}
I receive a list of items with name and ratings. And I want to filter with select. If I want to see just items with 5 rating or greater, select 5.
return (
<div className="container clearfix">
{/* value={props.search} */}
<select>
<option value="" />
<option value="10">10</option>
<option value="9">9</option>
<option value="8">8</option>
</select>
<div>
{props.results
.map(item=> (
<div key={item.id} className="item-holder">
<img src={`${imagePath}${item.image}`} />
<span className="votes">{item.rating}</span>
<p>{item.title}</p>
</div>
))}
</div>
</div>
);
TX!
You need to attach a listener to Select e.g.
<Select onChange={(event) => this.setState({filterValue: event.target.value})}
then you can filter the results with
props.results.filter((item) => item.rating >= this.state.filterValue)
.map(...)