Disable specific option from react-select isMulti reactjs - javascript

How should I disable specific options from react-select isMulti based on the condition provided.
import Select from 'react-select'
const Systems = () => {
const [dataSystems, setdataSystems] = useState([])
const [systemDetails, setsystemDetails] = useState({
SYSTEMID: 1,
......
})
const getSystems = async() => {
await axios.get('/API')
.then(response => {
setdataSystems(response.data)
})
}
const [multiSelected, setmultiSelected] = useState();
var handleMultiSelect = (e) => {
setmultiSelected(Array.isArray(e)?e.map(x=> x.value):[]);
}
const bodyInsertDepSystem = (
.......
<Select
isMulti
options = {dataSystems.map(e => ({ label: e.SYSTEMALIAS, value: e.SYSTEMID }))}
onChange = {handleMultiSelect} > </Select>
)
}
What I want to do is to remove the disable the SYSTEMID from the dropdown that has same ID as systemDetails.SYSTEMID.
Hope that you can help me with this.
What I really doing on this: During edit I want to relate one SYSTEMID to multiple SYSTEMID but I want to disable or remove that has same SYSTEMID

<Select
isMulti
options = {dataSystems.map(e => ({
label: e.SYSTEMALIAS,
value: e.SYSTEMID
isDisabled: e.SYSTEMID == systemDetails.SYSTEMID ? true: null
}))}
onChange = {handleMultiSelect}>
</Select>

Related

My sort is not being rerendered as I want to sort datas according to the user selection

My sorting is working but sometimes my data doesnot change as I select the option no change occurs , I guess I am not using useEffect correctly So I want what am I doing wrong , I am very confused
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
property?.map((item) => (
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}
I think your problem is you're using property?.map which is always referred to your original list.
For a possible fix, you could modify it to data?.map which is your sorted list.
And you also need to set a default value for data
const [data, setData] = useState(property); //`property` is from your fetched data
Full change can be
const { data: property, isFetching, refetch } = useQuery(['PropertySearch', startDate, endDate, where, adultCount, childCount], propertyAvaibility, {
retry: false,
enabled: !!data
})
const [data, setData] = useState(property); //set `property` as your default data
const [sortType, setSortType] = useState('rating');
useEffect(() => {
const sortArray = type => {
const types = {
number_of_bars: 'number_of_bars',
starting_price: 'starting_price',
};
const sortProperty = types[type];
const sorted = property?.sort((a, b) => b[sortProperty] - a[sortProperty]);
setData(sorted);
};
sortArray(sortType);
}, [sortType]);
const displayedData = data?.length ? data : property //check if data is available
<select onChange={(e) => setSortType(e.target.value)} className="form-control">
<option value="number_of_bars">number_of_bars</option>
<option value="starting_price">starting_price</option>
</select>
{
displayedData?.map((item) => ( //the main change is here
<PropertyCard
key={item?.id}
title={item?.title}
image={item?.cover_image?.url}
location={item.address}
displayFooter={false}
displayButton={false}
rating={true}
item={item}
type={item?.brand_name}
link="property">
{item?.description?.slice(0, 150)}
</PropertyCard>
))
}

error while setting variants option array Cannot read property '0' of undefined

hello iam creating an ecomerce shop in my chec dasboard i set variants of sizes large small but when i try to implement options drop down on options array i get the error Cannot read property '0' of undefined in line12 which is let finalSizeArray = props.product.variants[0].options.map(option =
productcard.js
import React, { useState, useEffect } from 'react';
import { Card, Image, Button, Icon, Dropdown } from 'semantic-ui-react';
const ProductCard = (props) => {
console.log(props.product, 'props from Container')
const [sizes, setSizes] = useState([])
const [variantInfo, setVariantInfo] = useState()
useEffect(() => {
let finalSizeArray = props.product.variants[0].options.map(option => {
let sizeInfo = {}
sizeInfo.key = option.name
sizeInfo.text = option.name
sizeInfo.value = option.id
return sizeInfo
})
setSizes(finalSizeArray)
}, [])
const handleSize = (e, {value}) => {
setVariantInfo({[props.product.variants[0].id]: value})
}
const handleButtonAddCart = e => {
e.preventDefault()
props.addToCart(props.product.id, variantInfo)
// Funtion to Clear Select Input for Dropdown - Needs work.
// let selectInput = document.querySelectorAll('.sizes-drop')
// selectInput.forEach((input,i) => {
// input.children[0].innerHTML = 'Select Size'
// // input.children[0].classList.add('default')
// })
}
return (
<Card>
<Image src={props.product.media.source} />
<Card.Content>
<Card.Header>{props.product.name}</Card.Header>
<Card.Meta>{props.product.price.formatted_with_symbol}</Card.Meta>
<Card.Description>{props.product.description.replace(/(<([^>]+)>)/ig,"")}</Card.Description>
<Dropdown
className="sizes-drop"
fluid
placeholder='Select Size'
selection
options={sizes}
/>
<Button fluid className='add-button' onClick={handleButtonAddCart}>
Add to Cart
<Icon name='arrow right' />
</Button>
</Card.Content>
</Card>
);
};
export default ProductCard;
I thinks its because your props not yet loaded...
You can give handle to your code like this
useEffect(() => {
let finalSizeArray = props?.product?.variants[0]?.options?.map(option => {
let sizeInfo = {}
sizeInfo.key = option.name
sizeInfo.text = option.name
sizeInfo.value = option.id
return sizeInfo
})
setSizes(finalSizeArray)
}, [])

How to filter items using function in React

I'm using a react select to filter my movies by categories but my function is not working, when I click on the element to filter, it delete all the movies on the UI
This is my Filter components :
import React from 'react';
import Select from 'react-select';
const CategoriesFilter = ({categories, filterMovie}) => {
const options = categories.map((c) => ({ value: c, label: c }));
return (
<div>
<Select
className="select-option"
options={options}
placeholder={"type something"}
onChange={filterMovie}
/>
</div>
)
}
export default CategoriesFilter;
This is my filter function and state from my APP js
const [moviesList, setMoviesList] = useState(MoviesData);
const filterMovie = (category) => {
const filterMovie = MoviesData.filter((movie)=> movie.category === category);
setMoviesList(filterMovie);
}
Where do you think the problem comes from?
Thank you guys
The problem is that your callback function is receiving the object you set into Select
const options = categories.map((c) => ({ value: c, label: c }));
and you are comparing
const filterMovie = MoviesData.filter((movie)=> movie.category === category);
it should be
const filterMovie = MoviesData.filter((movie)=> movie.category === category.value);
Check:
const CategoriesFilter = ({ categories, filterMovie }) => {
const options = categories.map((c) => ({ value: c, label: c }));
return (
<div>
<Select
className="select-option"
options={options}
placeholder={"type something"}
onChange={filterMovie}
/>
</div>
);
};
const MoviesData = [
{
title: "Foo",
category: "horror"
}
];
export default function App() {
const [moviesList, setMoviesList] = useState(MoviesData);
const filterMovie = (category) => {
console.log(category);
const filterMovie = MoviesData.filter(
(movie) => movie.category === category.value
);
setMoviesList(filterMovie);
};
console.log(moviesList);
return (
<div className="App">
<CategoriesFilter
categories={["horror", "action"]}
filterMovie={filterMovie}
/>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

How to pass value through props to another component and error : `Use the defaultValue or value props on instead of setting selected on <option>`?

I am trying to pass the selected value through the prop: handle state change, but I am getting two errors.
Error 1 : Use the defaultValue or value props on instead of setting selected on <option>
Error 2 : cannot read property 'active' of undefined at StateData
import React,{useState,useEffect} from 'react';
import { FormControl , makeStyles, InputLabel,Select} from '#material-ui/core';
import {options} from '../../api/api'
const useStyles = makeStyles((theme) => ({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}));
const ComboBox = ({handleStateChange}) =>{
const styles = useStyles();
const [fetchedStates,setFetchedStates] = useState([]);
const [ value , setValue] = useState('')
useEffect(()=>{
const fetchAPI = async() => {
setFetchedStates(await options());
}
fetchAPI()
},[setFetchedStates]);
const inputEvent = (e) =>{
console.log(e.target.value)
setValue(e.target.value)
handleStateChange(e.target.value)
}
return (
<div>
<FormControl variant="outlined" className={styles.formControl}>
<InputLabel>States</InputLabel>
<Select
defaultValue=''
value={value}
onChange={inputEvent}
label="States"
>
{fetchedStates.map((states, i) => <option key={i} value={states}>{states}</option>)}
</Select>
</FormControl>
</div>
);
}
export default ComboBox
//***This is where the API call happens***//
var url = 'https://api.covid19india.org/data.json';
export const StateData = async(states) =>{
let stateName = 'Nagaland'
if(states){
stateName = {states}
}
const response =await fetch(url);
const data = await response.json();
const pop = data.statewise;
const index = pop.findIndex(st => st.state === stateName)
const statedta = {
active :pop[index].active,
confirmed : pop[index].confirmed,
deaths : pop[index].deaths,
recovered: pop[index].recovered
}
return statedta
}
export async function ChartData() {
try{
let response = await fetch(`https://api.covid19india.org/data.json`);
return await response.json()
.then(data=>{
const pop = data.cases_time_series
const modifiedData = pop.map((totalData)=>({
confirmed : totalData.totalconfirmed,
deaths : totalData.totaldeceased,
recovered : totalData.totalrecovered,
date : totalData.date
}))
return modifiedData;
});
}catch(err){
console.error(err);
}
}
export async function options() {
const response =await fetch(url);
const data = await response.json();
const pop = data.statewise.map(st=>st.state);
return pop
}
You need to make few fixes.
Use NativeSelect if you are using your own options.
There was a bug in StateData fun. Don't put states in an object.
use a separate useEffect to call StateDatafun.
All your issues are fixed. See working demo of your code
jsx snippet
export default function ComboBox({ handleStateChange }) {
const [fetchedStates, setFetchedStates] = useState([]);
const [value, setValue] = useState("");
const [individualStateDetails, setIndividualStateDetails] = useState("");
useEffect(() => {
const fetchAPI = async () => {
setFetchedStates(await options());
};
fetchAPI();
}, [setFetchedStates]);
useEffect(() => {
if (fetchedStates.length) {
StateData(value).then(data => {
setIndividualStateDetails(data);
});
}
}, [value]);
const inputEvent = e => {
console.log(e.target.value);
setValue(e.target.value);
handleStateChange(e.target.value);
};
const [age, setAge] = React.useState("");
const handleChange = event => {
setAge(event.target.value);
};
return (
<div>
<FormControl variant="outlined">
<InputLabel>States</InputLabel>
<NativeSelect
defaultValue=""
// value={value}
onChange={inputEvent}
label="States"
>
{fetchedStates.map((states, i) => (
<option key={states + i} value={states}>
{states}
</option>
))}
</NativeSelect>
</FormControl>
<div>
{individualStateDetails &&
JSON.stringify(individualStateDetails, null, 2)}
</div>
</div>
);
}

Get a specific data from URL

{ _id: 5d8b8,
given_name: 'Abi',
family_name: 'Abi',
email: 'AAA#jwt.org',
password:'password'
}
I have this data and I want to get only email.
const url = 'http://localhost:9098/api/users'
const [users, setUsers] = useState([])
useEffect(() => {
axios.get(url).then(json => setUsers(json.data))
}, [])
const getEmail = () => {
return users.map(user => {
return (
<option> {user.email} </option>
)
})
}
<select onChange={handleAddMessage}
value={message.sender}
name="sender" id="sender"required>
<option>{getEmail()} </option>
</select>
This is how I am trying to do it .I need an easy way to extract email from this data into
I think that the value attribute has to be inside the option tag.As i can see you are rendering an option tag inside an option tag because the getEmail is returning a option tag:
<option>{getEmail()} </option>
So the approcach that i came up is to make a method that renders the options based on your list:
this.renderEmails = ( ) => {
let optionList = users.map(user => {
return (
<option value={ user.email }> {user.email} </option>
)
})
return optionList
};
And in your render method:
<select onChange={handleAddMessage}
name="sender" id="sender"required>
{ this.renderEmails() }
</select>
Extract the email when you get the data. Itterate through the data using forEach and store it to a variable and finally set it to the users-state
Later you can use users.map() to display the email ID
const url = 'http://localhost:9098/api/users';
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get(url).then(json => {
let usersResponse = []; json.data.forEach((data) => {
usersResponse.push(data.email);
});
setUsers(usersResponse)
})
}, []);
< select
onChange = { handleAddMessage }
value = { message.sender }
name = "sender" id = "sender" required
>
{
users.map((email) => {
<option>{email} </option>
})
}
</select >

Categories