I want to clear/remove/reset select options from dropdown itself and not from external button or allowClear
Let's say the icon of a trash in select option will reset all values:
However, I'm quite stuck on how to reset the value with this my current following code:
import st from "./AddToCartDropdown.module.css";
import {useState} from 'react';
import { Select } from 'antd';
import { DeleteFilled } from '#ant-design/icons';
const { Option } = Select;
function loopStock(n, selectedIndex){
var elements = [];
for(let i = 1; i <= n; i++){
const qty = new String(i);
const resultQty = qty.concat(" in cart");
elements.push(<Option value={i}> <span className={st.addToCartSelect}> {i === selectedIndex ? resultQty : i} </span></Option>);
}
return elements;
}
const AddToCart = () => {
const [selectedIndex, setSelectedIndex] = useState(-1);
const onChange = (newSelectedIndex) => {
setSelectedIndex(newSelectedIndex);
}
return (
<div >
<Select defaultValue="Add to Cart" onChange={onChange} className={st.addToCartDefault} bordered={false}>
<Option value="delete"> <DeleteFilled /> </Option>
{loopStock(5, selectedIndex)}
</Select>
</div>
);
};
export default AddToCart;
When I select the trash icon, it supposed to show me Add to Cart instead of trash icon:
The problem is I'm confused how to set the state after I selected the icon of trash in order to reset all options and go back to Add to Cart default value of Select.
I'm new to React/JavaScript and still learning. After searching all solutions, I think it's the best to create my own question in here. Thanks!
You can make your select as a controlled component by passing a value prop and having a state. set the initial state to null instead of -1 so that we can use the placeholder.
const [selectedIndex, setSelectedIndex] = React.useState(null);
when the selected value is delete we are setting the state to null
const onChange = (newSelectedIndex) => {
if(newSelectedIndex === 'delete'){
setSelectedIndex(null)
}else {
setSelectedIndex(newSelectedIndex)
}
}
Now add the value and placeholder prop in your select.
<Select placeholder="Add to Cart" value={selectedIndex} onChange={onChange} bordered={false}>
<Option value="delete"> <DeleteFilled /> </Option>
{loopStock(5, selectedIndex)}
</Select>
Related
My API is returning below result.
I have below code to display in list.
const [result,setResult] = useState([]);
const fetchStatus = async ()=>{
await httpClient.get( config.resourceServerUrl+"/certificates/status").then(res=>{
setResult(res.data);
setActive(true);
alert(result);
})
and I am displaying list like below.
<div className="col-md-4">
<label htmlFor="status">Status</label>
<select
name="requestStatus"
style={{ display: 'block' }}>
<option value="" selected >
Please Select the Status
</option>
{
active && result.map((sts:any)=>{
<option key="" value="">
{sts}
</option>
})
}
</select>
though there is no error but it is not displaying anything.
Its because you've got {} around your JSX, should be ()
active && result.map((sts:any) => (
<option>{sts}</option>
))
or you can do
active && result.map((sts:any) => {
return (
<option>{sts}</option>
)
})
I don't believe you await httpClient.get. The .then will be called when the get completes.
you are setting the dropdown to each object in the returned array. You want to set it to the value of the request_status key: sts.request_status
set the key attribute for elements you create using map
{
active && result.map((sts:any)=>{
{sts.request_status}
})
}
The problem is:
There is a landing page, a language switch added with ant design, specifically, through Select / Option. The translation was done via i18react lib.
So, it is necessary that when the page is reloaded, the selected language is displayed in the dropdown itself, and not reset to the default Language.
I know what can be done through document.cookie. But how? Well, I'll put languages in cookies. And then, how to screw them into this Select so that the display of the selected language is saved on reboot?
My code is here and I don't know what to do.
const Option = Select.Option;
function ChangeLanguageDropdown({}) {
const {i18n} = useTranslation();
const changeLanguage = (lang) => {
i18n.changeLanguage(lang);
};
Cookies.set('ru', 'Русский', { expires: 7 });
Cookies.set('en', 'English', { expires: 7 });
return (
<div>
<Select defaultValue={"Language"} style={{ width: 110}} onChange={changeLanguage}>
<Option value="ru">{i18next.t("Русский")}</Option>
<Option value="en">{i18next.t("English")}</Option>
</Select>
</div>
const {useState} = React
const { Select } = antd
const { Option } = Select;
const ChangeLanguageDropdown = ({}) => {
const [lang, setLang] = useState('en' /* Cookie.get('path.to.cookie') */);
const changeLanguage = (lang) => {
setLang(lang);
/* Cookie.set('path.to.cookie', lang); */
/* call i18n.changeLanguage(lang); */
};
return (
<div><div>{lang}</div>
<Select defaultValue={lang} style={{ width: 500}} onChange={changeLanguage}>
<Option value="ru">"Русский"</Option>
<Option value="en">"English"</Option>
</Select>
</div>);
}
ReactDOM.render(<ChangeLanguageDropdown />, document.body)
Note that I've removed all i18n related code as well as Cookie lib (your setup of Codepen was #R%T$). Next time, start with some example that actually works (e.g. https://codepen.io/mugiseyebrows/pen/ExyJJQQ?editors=1111)
I'm trying to make this app, it's a simple react app with google books API. My question is how can I filter rendered elements depending on select value? I've tried useEffect and .filter method but I just can't figure it out. Here's what I got so far:
function App() {
const[book, setBook] = useState("");
const[result, setResult] = useState([]);
const[apiKey, setApiKey] = useState("MY API KEY");
const[sortBy, setSortBy]= useState("relevance")
const [categorie, SetCategorie]= useState("all")
function handleChange(event){
const book = event.target.value;
setBook(book)
};
function handleSubmit(event){
event.preventDefault()
axios.get("https://www.googleapis.com/books/v1/volumes?q="+book+"&key="+apiKey+"&maxResults=30&orderBy="+sortBy)
.then(function(res){
setResult(res.data.items)
console.log(res.data.items)
})
};
And that's when the problem starts
useEffect(function(){
result.filter(function(book){
const filteredBooks =
book.volumeInfo.categories.includes(categorie)
console.log(book)
})
},[categorie])
return (
<div className="container mt-4 ">
<h1>Search for books API</h1>
<form onSubmit={handleSubmit}>
<div className="form-group ">
<input onChange={handleChange}
type="text" className="form-control "
autoComplete="off"
placeholder="enter book name">
</input>
</div>
<button type="submit" className="btn btn-success"> Search now</button>
<select onChange={function(event){
let selectedSortBy = event.target.value;
setSortBy(selectedSortBy)
}}>
I've also needed to change API requests with select values, but that bit seems to work fine
<option value="relevance">Relevance</option>
<option value="newest">Newest</option>
</select>
</form>
<select onChange = {function(event){
let selectedCategorie = event.target.value;
SetCategorie(selectedCategorie);
}}>
<option value="all">All</option>
<option value="Art">Art</option>
<option value="Biography">Biography</option>
<option value="Computers">Computers</option>
<option value="History">History</option>
<option value="Medical">Medical</option>
<option value="Poetry">Poetry</option>
</select>
<div class="row">
{result.map(book => {
return <div class="col">
<div class="box">
<Card
img = {book.volumeInfo.imageLinks === undefined
? ""
: `${book.volumeInfo.imageLinks.thumbnail}`}
category = {book.volumeInfo.categories}
title = {book.volumeInfo.title}
authors = {book.volumeInfo.authors}
/>
</div>
</div>
})}
</div>
</div>
);
}
export default App;
As I understand, you have select component which contains book categories list and once user changes the category you wish to show books only with selected categories.
const onCategoryChange = (event) => {
const selectedCategory = event.target.value;
const filteredBooks = result.filter((book) =>
book.volumeInfo.categories.includes(selectedCategory));
setCategories(selectedCategory);
setResult(filteredBooks);
};
<select onChange = {onCategoryChange}>
Get all categories
Filter out the books using the categories
Set categories and books.
Im not too familiar with react hooks, however if I understand correctly the function runs every time the category variable changes. The filter method needs to return truish value if you want to keep an item and falseish if not. It creates a new array which is returned. In your case you only set a const and log a value, returning void (implicit).
This should update the result to match your filtered books.
useEffect(function(){
result = result.filter(function(book){
const includesCategory = book
.volumeInfo
.categories
.includes(categorie);
console.log(book)
return includesCategory;
})
},[categorie])
Problem
Hi devs,
I am building an app of movies and series with an api that I developed. I have the problem that when I want to access a video section it does not let me in since the value of season_list [season_selected - 1] .episodes is undefined.
I have three options available in the section:
1 Option: Select season
2 Option: Select chapter
3 Option: Select videos
I can enter the section if I change javascripts season_list [season_selected - 1].episodes by javascripts season_list[season_selected - 1].
Here is the example of json, particularly in the part of season_list
https://cinemanight.chrismichael.now.sh/api/v1/search/elite
You will notice that the season_list has two values, season and episodes. This is why I need to use episodes like season_list [season_selected - 1] .episodes
Error
"vue.runtime.esm.js? 2b0e: 1888 TypeError: Cannot read property 'episodes' of undefined"
The error is referring to the following line
season_list[season_selected - 1].episodes
Template Section
<select class="container" v-model="season_selected">
<option disabled value="">Temporadas</option>
<option v-for="(season , index) in Array.from({length: total_seasons}, (v , k) => k + 1)" :value="season" :key="index">
{{ season }}
</option>
</select>
<select class="container" v-model="episode_selected">
<option disabled value="">Episodios</option>
<option v-for="(epis , index) in season_list[season_selected - 1].episodes" :value="epis" :key="index">
{{ epis }}
</option>
</select>
<select class="container" v-model="option">
<option disabled value="">Videos</option>
<option v-for="(video , index) in serie_video.map(xs => xs.iframe)" :value="video" :key="index">
{{ video }}
</option>
</select>
Script Section
<script>
import {value , watch} from 'vue-function-api';
import {useState , useStore , useRouter} from '#u3u/vue-hooks';
export default{
name: 'SerieVideo',
setup(){
const store = useStore();
const {route} = useRouter();
const state = {
...useState(['serie_video' , 'isLoading'])
};
const params = {
id: value(route.value.params.id),
title: value(route.value.params.title),
sinopsis: value(route.value.params.sinopsis),
extra: value(route.value.params.extra)
};
const values = {
title: params.title.value,
sinopsis: params.sinopsis.value,
channel: params.extra.value[0].channel,
first_air_date: params.extra.value[0].first_air_date.replace('First air date' , ''),
last_air_date: params.extra.value[0].last_air_date.replace('Última transmisión' , ''),
creator_member: params.extra.value[0].cast_members,
members_list: params.extra.value[0].cast_members,
season_list: params.extra.value[0].season_list
};
const total_seasons = value(values.season_list);
const season_list = value(values.season_list);
const season_selected = value(null);
const episode_selected = value(null);
const id = value(null)
const option = value("");
watch(() =>
episode_selected.value , (value) =>{
episode_selected.value = value;
const eps = episode_selected.value;
const id = `${params.id.value.replace('ver-' , '')}-${eps}`
store.value.dispatch("GET_VIDEO_SERIES" , id)
}
);
return{
...state,
...values,
option,
season_selected: season_selected.value,
episode_selected: episode_selected.value,
season_list: season_list.value,
total_seasons: total_seasons.value.length
}
}
}
</script>
I have a solution but it has a bug
And is that in episodeList every time I select a season it makes me push and if I choose the same season again it makes me push. And I can see this quickly when I have a select for episodes, it shows me a list of the seasons I have selected and not just one.
I want to find a way not to push using episodesList
Template seccion
<select class = "container" v-model = "episode_selected">
<option disabled value = ""> Episodes </option>
<option v-for = "(epis, index) in episodesList [season_selected - 1]": value = "epis": key = "index">
{{epis}}
</option>
</select>
Sscript Seccion
const episodesList = value ([])
watch (() =>
season_selected.value, (value) => {
season_selected.value = value
const selected = season_selected.value; // season selected
episodesList.value.push (season_list [selected - 1] .episodes); // list of episodes
}
);
FINAL SOLUTION
Problem corrected by adding the value 1 to the variable const season_selected = value(1);. Then a watch will be used to be aware that its value is updated.
Setting the value 1 will let me start the video section and having season 1 selected. But then the user can make the change in the select.
We are working on a project where we are using boxes, and need one of the select boxes to perform an action when the user selects an item from the list. This is our first time touching React, let alone building a project, so we are stumped at this point. What we are using for the onChange code is as follows:
var React = require('react');
var ReactPropTypes = React.PropTypes;
var ProgramSelectorComponent = React.createClass({
propTypes: {
allPrograms: ReactPropTypes.array.isRequired
},
_updateProgram: function(e) {
this.setState({
value: "TEST"
});
},
render() {
var Programs = this.props.allPrograms;
var options = Programs.map(function (prog) {
return <option key={ prog.program_id } value={ prog.program_id } >
{ prog.program_name }
</option>;
});
return (
<select className="form-control margin-bottom" name="Program" id="programSelect" ref="progRef" onChange={this._updateProgram} >
<option value="select">Select</option>
{options}
</select>
)
}
});
module.exports = ProgramSelectorComponent;
I know that rendering does work in the <select> tag as I can add something like data-test-id="test" and that renders properly, but for some reason, the onChange is not showing in the code, and therefore, not working.
Like I said, we are all new to this, so any help would be greatly appreciated.
In your select tag try: <select value={this.state.value}>
This is a good read about controlled vs uncontrolled components: https://facebook.github.io/react/docs/forms.html