I'm trying to implement my own Autocomplete component using useAutocomplete hook from mui/base package. Everything works as expected apart from disabled option.
My understanding is that the component should not be intractable with.
Example below comes from documentation with added disabled: true option.
How can I force this component to stay closed even if the user clicks when it is disabled?
Code sandbox link
import * as React from "react";
import { useAutocomplete } from "#mui/base/AutocompleteUnstyled";
import { styled } from "#mui/system";
const options = [
{ title: "The Shawshank Redemption", year: 1994 },
{ title: "The Godfather", year: 1972 },
{ title: "The Godfather: Part II", year: 1974 }
];
const Label = styled("label")({
display: "block"
});
const Input = styled("input")(({ theme }) => ({
width: 200,
backgroundColor: theme.palette.mode === "light" ? "#fff" : "#000",
color: theme.palette.mode === "light" ? "#000" : "#fff"
}));
const Listbox = styled("ul")(({ theme }) => ({
width: 200,
margin: 0,
padding: 0,
zIndex: 1,
position: "absolute",
listStyle: "none",
backgroundColor: theme.palette.mode === "light" ? "#fff" : "#000",
overflow: "auto",
maxHeight: 200,
border: "1px solid rgba(0,0,0,.25)",
"& li.Mui-focused": {
backgroundColor: "#4a8df6",
color: "white",
cursor: "pointer"
},
"& li:active": {
backgroundColor: "#2977f5",
color: "white"
}
}));
export default function Autocomplete() {
const {
getRootProps,
getInputLabelProps,
getInputProps,
getListboxProps,
getOptionProps,
groupedOptions,
value,
popupOpen
} = useAutocomplete({
id: "use-autocomplete-demo",
disabled: true, // Component shouldn't be interactable
options: options,
getOptionLabel: (option) => option.title
});
return (
<div>
<p>value: {JSON.stringify(value)}</p>
<div {...getRootProps()}>
<Label {...getInputLabelProps()}>useAutocomplete</Label>
<Input {...getInputProps()} />
</div>
{popupOpen ? (
<Listbox {...getListboxProps()}>
{(groupedOptions as typeof options).map((option, index) => (
<li {...getOptionProps({ option, index })}>{option.title}</li>
))}
</Listbox>
) : null}
</div>
);
}
I believe this is a bug in useAutocomplete hook, although I might be wrong.
For my use case, I fixed this issue by overwriting onMouseDown callback in rendered input
<Input {...getInputProps()} {...(props.disabled && { onMouseDown: undefined })} />
props.disabled above is a prop passed into my custom component
Related
Im using react and displaying some labels via the array object of labels. Now, I want to do this dynamically. So if a user clicks a button, the object updates and the user interface should update accordingly as well. The issue here is that I got the array to update after clicking on the button, as evidenced by a console log line that I wrote in the onclick handler. But the user interface does not update accordingly. Just the array shows the values. Here is what the inital array looks like:
const labelsArray = [
{ label: 'Hey There', sublabel1: 'How are you?' },
{
label: 'Greetings', sublabel1: 'Fellows'
},
{ label: 'Awesome', sublabel1: 'Youre doing great', sublabel2: 'cool' }
];
I want to append a warningLabel, and errorLabel to the 2nd object of this array. So since arrays are 0 indexed, I did the following in the onclick handler:
const appendLabel = async () => {
labelsArray[1].warningLabel = "Hello";
labelsArray[1].errorLabel = "Hello";
console.log(labelsArray)
};
The array updates, but not the user interface. Which is really weird.
Also, this is not related to react state mutation, which I know because of my research of this topic when I was trying to figure it out. So just to be clear, its not about state mutation, which might have someone put this as a duplicate question. Its more of a react/object structure question. But I could be wrong! Anyways, any help is appreciated. Thanks!
Here is my whole component for reference
import React, { useState } from 'react';
import { Button, Typography } from '#material-ui/core';
import { withStyles } from '#material-ui/core/styles/';
import Stepper from '#material-ui/core/Stepper';
import Step from '#material-ui/core/Step';
import StepLabel from '#material-ui/core/StepLabel';
import StepConnector from '#material-ui/core/StepConnector';
import PropTypes from 'prop-types';
const styles = theme => ({
stepLabelRoot: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
},
checklistHeader: {
fontWeight: 'bold',
marginTop: '80px'
},
connectorIcon: {
color: theme.palette.text.secondary
},
stepper: {
background: 'none',
fontWeight: 'bold'
},
checkListImageContainer: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center'
},
connector: {
},
activeConnector: {
border: 'solid 1px #6fef71'
},
stepIcon: {
height: '35px',
width: '35px',
'&:hover': {
backgroundColor: 'rgba(134, 141, 150, 0.37)',
borderRadius: '50%'
},
},
activeStepIcon: {
backgroundColor: 'yellow'
},
label: {
fontWeight: 'bold',
display: 'flex',
fontSize: '15px'
},
sublabel: {
fontWeight: 'normal',
fontSize: '13px'
},
errorLabel: {
color: 'red'
},
warningLabel: {
color: 'yellow'
},
step: {
'&$completed': {
color: 'lightgreen'
},
'&$active': {
color: 'pink'
},
'&$disabled': {
color: 'red'
},
},
alternativeLabel: {},
active: {
}, // needed so that the &$active tag works
completed: {
},
disabled: {
},
labelContainer: {
'&$alternativeLabel': {
marginTop: 0
},
},
});
const labelsArray = [
{ label: 'Random text?', sublabel1: 'Lorem Ipsum' },
{
label: 'Another random text', sublabel1: 'Hello World'
},
{ label: 'Cool', sublabel1: 'cool', sublabel2: 'ayo' }
];
const Checklist = ({ classes,activeStep }) => {
return (
<React.Fragment>
<Stepper alternativeLabel activeStep={2} connector={<StepConnector />} className={classes.stepper}>
{labelsArray.map(label => (
<Step key={label} completed>
<StepLabel active
completed
StepIconProps={{
classes: {
root: classes.step,
completed: classes.completed,
active: classes.active,
disabled: classes.disabled
}
}}>
<div className={classes.stepLabelRoot}>
<span className={classes.label}>
{label.label}
</span>
<span className={classes.sublabel}>
{label.sublabel1}
</span>
<span className={classes.sublabel}>
{label.sublabel2}
</span>
<span className={classes.sublabel}>
{label.sublabel3}
</span>
<span className={classes.errorLabel}>
{label.errorLabel && <img src="/static/images/lock-material.png" alt="img" style={{ height: '15px', width: '15px' }} />}
{label.errorLabel}
</span>
<span className={classes.warningLabel}>
{label.warningLabel && <img src="/static/images/warning-sign.png" alt="img" style={{ height: '15px', width: '15px' }} />}
{label.warningLabel}
</span>
</div>
</StepLabel>
</Step>
))}
</Stepper>
<Button onClick={() => appendLabel()}>Hello</Button>
</React.Fragment>
);
};
Checklist.defaultProps = {
activeStep: -1
};
Checklist.propTypes = {
classes: PropTypes.object.isRequired,
form: PropTypes.bool.isRequired,
activeStep: PropTypes.number
};
export default withStyles(styles, { withTheme: true })(Checklist);
You need to set the labelsArray in the state and update it accordingly in order to re-render the component when the user clicks the button
Edited:
A way of doing that with a state would be:
const LABELS =[
{ label: 'Hey There', sublabel1: 'How are you?' },
{ label: 'Greetings', sublabel1: 'Fellows' },
{ label: 'Awesome', sublabel1: 'Youre doing great', sublabel2: 'cool' }
];
const [labelsArray, setLabelsArray] = useState(LABELS);
const appendLabel = () => {
let editedLabels = [...labelsArray];
editedLabels[1].warningLabel = "Hello";
editedLabels[1].errorLabel = "Hello";
setLabelsArray(editedLabels);
};
I am using material-table with my react project.
How I can center table title ?
Here is codesandbox example:
https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js
I want to make title "Average Expense ratio" to be in the center:
I tried adding style prop to the MaterialTable with textAlign:"center" but it does not work. Is it even possible to do it?
You can override Toolbar component and provide custom title react component if required.
import "./styles.css";
import MaterialTable, { MTableToolbar } from "material-table";
import Typography from "#material-ui/core/Typography";
const MyNewTitle = ({ text, variant }) => (
<Typography
variant={variant}
style={{
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis"
}}
>
{text}
</Typography>
);
export default function App() {
const softRed = "#CC6666";
//GREENS
const forestgreen = "#556B2F";
const limegreen = "#228B22";
const lightgreen = "#3CB371";
//ORANGES
const softOrange = "#ffd27f";
return (
<div className="App">
<MaterialTable
style={{}}
title={<MyNewTitle variant="h6" text="Average Expense Ratio" />}
components={{
Toolbar: (props) => (
<div
style={{
alignItems: "center",
justifyContent: "center",
display: "flex"
}}
>
<MTableToolbar {...props} />
</div>
)
}}
columns={[
{
title: "0.19 and below",
field: "first",
headerStyle: {
backgroundColor: forestgreen
}
},
{
title: "0.20 to 0.48",
field: "first",
headerStyle: {
backgroundColor: limegreen
}
},
{
title: "0.49 to 0.77",
field: "first",
headerStyle: {
backgroundColor: lightgreen
}
},
{
title: "0.78 to 1.06",
field: "first",
headerStyle: {
backgroundColor: softOrange
}
},
{
title: "1.07 and above",
field: "first",
headerStyle: {
backgroundColor: softRed
}
}
]}
data={[]}
options={{
headerStyle: {
color: "#FFF",
textAlign: "center",
whiteSpace: "nowrap",
fontSize: 10
},
paging: false,
search: false,
sorting: false,
showEmptyDataSourceMessage: false
}}
/>
</div>
);
}
I want to change the background color of my material ui datepicker modal
import { createMuiTheme } from "#material-ui/core";
const materialTheme = createMuiTheme({
overrides: {
MuiPickersToolbar: {
toolbar: {
backgroundColor: 'red',
},
},
MuiPickersDay: {
day: {
color: 'black',
},
daySelected: {
backgroundColor: '#33abb6',
},
dayDisabled: {
color: '#ccc',
},
current: {
color: 'red',
},
},
MuiPickersModal: {
dialogAction: {
color: '#33abb6',
},
},
},
});
export default materialTheme
In the above code i was able to change colors of date and few others but not the total background color
Are there any documentation from which i can get these class names or any other option
Try in CSS:
.MuiPaper-root {
background-color: #eaea87;
}
In recent version of MUI (v5.3.1) I resolved this issue by adding sx={{ backgroundColor: 'white' }} to TextField in renderInput prop as below:
<MobileDatePicker
label="Date"
value={date}
onChange={(newValue) => {
setDate(newValue);
}}
renderInput={(params) => (
<TextField
sx={{ backgroundColor: 'white' }}
fullWidth
{...params}
/>
)}
/>
You can use createTheme to provide component overrides (see docs):
const theme = createTheme({
components: {
// Name of the component
MuiInputBase: {
styleOverrides: {
// Name of the slot
root: {
// Some CSS
backgroundColor: "white",
// add variant styles like so
"&.Mui-disabled": {
"backgroundColor": "#cccccc"
}
},
},
},
},
});
You can see the name of the component to use by inspect element and looking at the class names, and you can find the slots in the component definition, e.g. this is the slots for the MuiInput component.
Also see this source on combining class names to target disabled, hover, active etc.
MuiPickers is using Dialog Material Ui, so override all dialog component that be used in this pickers. I'm not sure with this solution below. You can try this, hope it's worked.
const materialTheme = createMuiTheme({
overrides: {
MuiPickersToolbar: {
toolbar: {
backgroundColor: 'red',
},
},
MuiPickersDay: {
day: {
color: 'black',
},
daySelected: {
backgroundColor: '#33abb6',
},
dayDisabled: {
color: '#ccc',
},
current: {
color: 'red',
},
},
MuiPickersModal: {
dialogAction: {
color: '#33abb6',
backgroundColor: 'YOUR HEX HERE',
},
},
},
});
I think the good way is send style in DialogProps
https://material-ui-pickers.dev/api/DateTimePicker (section modal wrapper)
so then you can override all dialog modal.
I am trying to have a single onChange event for each element that is rendered with the map function. The problem is that for each letter that I write, it is as if the execution stops, preventing me from writing freely and seeing the changes I am making in the text field in the console.
Here you can see the error: https://codesandbox.io/s/tender-wu-kuzqd
const options = [
{ id: 1, hour: 0, minute: 0, enrollment: '', value: 'ac.terapeutico', label: 'Ac. Terapéutico', color: getRandomColor() },
{ id: 2, hour: 0, minute: 0, enrollment: '', value: 'kinesiologia', label: 'Kinesiología', color: getRandomColor() },
{ id: 3, hour: 0, minute: 0, enrollment: '', value: 'oncologia', label: 'Oncología', color: getRandomColor() }
];
const Form = () => {
const [selectedSpeciality, setSelectedSpeciality] = useState(null);
const handleChangeEnrollment = (value, id) => {
let index = selectedSpeciality.findIndex(el => el.id === id);
const data = [...selectedSpeciality];
data[index].enrollment = value;
setSelectedSpeciality(data);
}
return (
<Grid container spacing={2}>
<Grid item xs={12}>
<Select
closeMenuOnSelect={true}
isMulti
options={options}
styles={colourStyles}
value={selectedSpeciality}
onChange={setSelectedSpeciality}
placeholder='Seleccione especialidades'
noOptionsMessage={() => "No hay más opciones"}
/>
</Grid>
{selectedSpeciality &&
selectedSpeciality.map(el => (
<Fragment key={uuid()}>
<Grid item xs={6}>
<TextField
fullWidth
InputLabelProps={{
shrink: true,
}}
value={el.enrollment}
onChange={(e) => handleChangeEnrollment(e.target.value, el.id)}
label={`MATRÍCULA ${el.label.toUpperCase()}`}
/>
</Grid>
</Fragment>
))
}
{console.log(selectedSpeciality)}
</Grid>
);
}
The problem is that you are using Fragment with uuid, which create a new instance at each render.
This results in rendering the whole part again and losing focus.
You need to remove Fragment or use any other consistent key value for each element in map.
Without Fragment
See: https://codesandbox.io/s/lucid-field-crolh?file=/src/App.js
import React, { useState, Fragment } from "react";
import uuid from "react-uuid";
import styled from "styled-components";
import Select from "react-select";
import { Grid, TextField, Box } from "#material-ui/core";
export const StyleWrapper = styled.div`
.MuiInputBase-root {
font-size: 24px;
font-weight: 600;
color: #061655;
}
`;
const dot = (color = "#ccc") => ({
alignItems: "center",
display: "flex",
":before": {
backgroundColor: color,
borderRadius: 10,
content: '" "',
display: "block",
marginRight: 4,
marginLeft: 8,
height: 10,
width: 10
}
});
const colourStyles = {
control: (styles) => ({ ...styles, backgroundColor: "white" }),
option: (styles, { data, isDisabled, isFocused, isSelected }) => {
return {
...styles,
backgroundColor: isDisabled
? null
: isSelected
? data.color
: isFocused
? "000000"
: null,
color: isDisabled
? "#ccc"
: isSelected
? "000000" > 2
? "white"
: "black"
: "000000",
cursor: isDisabled ? "not-allowed" : "default",
":active": {
...styles[":active"],
backgroundColor: !isDisabled && (isSelected ? "000000" : "000000")
},
borderRadius: "10px"
};
},
placeholder: (styles) => ({ ...styles, ...dot() }),
multiValue: (styles, { data }) => ({
...styles,
...dot(data.color),
borderRadius: "40px"
}),
multiValueLabel: (styles) => ({
...styles,
color: "#061655",
fontWeight: 500
}),
multiValueRemove: (styles, { data }) => ({
...styles,
color: "#061655",
padding: "8px 8px 8px 4px",
":hover": {
backgroundColor: "#transparent",
color: "#061655",
cursor: "pointer",
borderRadius: "0px 40px 40px 0px"
}
})
};
const FormAddProfessional = (props) => {
const [selectedSpeciality, setSelectedSpeciality] = useState(null);
const optionsSpeciality = [
{
id: 1,
hour: 0,
minute: 0,
enrollment: "",
value: "ac.terapeutico",
label: "Ac. Terapéutico"
},
{
id: 2,
hour: 0,
minute: 0,
enrollment: "",
value: "kinesiologia",
label: "Kinesiología"
},
{
id: 3,
hour: 0,
minute: 0,
enrollment: "",
value: "oncologia",
label: "Oncología"
}
];
const handleChangeEnrollment = (value, id) => {
let index = selectedSpeciality.findIndex((el) => el.id === id);
const data = [...selectedSpeciality];
data[index].enrollment = value;
setSelectedSpeciality(data);
};
return (
<div style={{ width: "100%" }}>
<div style={{ paddingLeft: 4 }}>
<Box borderLeft={1} borderColor="#EBEBEB" style={{ padding: 12 }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Select
closeMenuOnSelect={true}
isMulti
options={optionsSpeciality}
styles={colourStyles}
value={selectedSpeciality}
onChange={setSelectedSpeciality}
placeholder="Seleccione especialidades"
noOptionsMessage={() => "No hay más opciones"}
/>
</Grid>
{selectedSpeciality &&
selectedSpeciality.map((el) => (
<Grid item xs={6}>
<TextField
fullWidth
InputLabelProps={{
shrink: true
}}
value={el.enrollment}
onChange={(e) =>
handleChangeEnrollment(e.target.value, el.id)
}
label={`MATRÍCULA ${el.label.toUpperCase()}`}
/>
</Grid>
))}
{console.log(selectedSpeciality)}
</Grid>
</Box>
</div>
</div>
);
};
export default FormAddProfessional;
With different consistent key value
See: https://codesandbox.io/s/angry-jang-8w004?file=/src/App.js:0-4014
import React, { useState, Fragment } from "react";
import uuid from "react-uuid";
import styled from "styled-components";
import Select from "react-select";
import { Grid, TextField, Box } from "#material-ui/core";
export const StyleWrapper = styled.div`
.MuiInputBase-root {
font-size: 24px;
font-weight: 600;
color: #061655;
}
`;
const dot = (color = "#ccc") => ({
alignItems: "center",
display: "flex",
":before": {
backgroundColor: color,
borderRadius: 10,
content: '" "',
display: "block",
marginRight: 4,
marginLeft: 8,
height: 10,
width: 10
}
});
const colourStyles = {
control: (styles) => ({ ...styles, backgroundColor: "white" }),
option: (styles, { data, isDisabled, isFocused, isSelected }) => {
return {
...styles,
backgroundColor: isDisabled
? null
: isSelected
? data.color
: isFocused
? "000000"
: null,
color: isDisabled
? "#ccc"
: isSelected
? "000000" > 2
? "white"
: "black"
: "000000",
cursor: isDisabled ? "not-allowed" : "default",
":active": {
...styles[":active"],
backgroundColor: !isDisabled && (isSelected ? "000000" : "000000")
},
borderRadius: "10px"
};
},
placeholder: (styles) => ({ ...styles, ...dot() }),
multiValue: (styles, { data }) => ({
...styles,
...dot(data.color),
borderRadius: "40px"
}),
multiValueLabel: (styles) => ({
...styles,
color: "#061655",
fontWeight: 500
}),
multiValueRemove: (styles, { data }) => ({
...styles,
color: "#061655",
padding: "8px 8px 8px 4px",
":hover": {
backgroundColor: "#transparent",
color: "#061655",
cursor: "pointer",
borderRadius: "0px 40px 40px 0px"
}
})
};
const FormAddProfessional = (props) => {
const [selectedSpeciality, setSelectedSpeciality] = useState(null);
const optionsSpeciality = [
{
id: 1,
hour: 0,
minute: 0,
enrollment: "",
value: "ac.terapeutico",
label: "Ac. Terapéutico"
},
{
id: 2,
hour: 0,
minute: 0,
enrollment: "",
value: "kinesiologia",
label: "Kinesiología"
},
{
id: 3,
hour: 0,
minute: 0,
enrollment: "",
value: "oncologia",
label: "Oncología"
}
];
const handleChangeEnrollment = (value, id) => {
let index = selectedSpeciality.findIndex((el) => el.id === id);
const data = [...selectedSpeciality];
data[index].enrollment = value;
setSelectedSpeciality(data);
};
return (
<div style={{ width: "100%" }}>
<div style={{ paddingLeft: 4 }}>
<Box borderLeft={1} borderColor="#EBEBEB" style={{ padding: 12 }}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Select
closeMenuOnSelect={true}
isMulti
options={optionsSpeciality}
styles={colourStyles}
value={selectedSpeciality}
onChange={setSelectedSpeciality}
placeholder="Seleccione especialidades"
noOptionsMessage={() => "No hay más opciones"}
/>
</Grid>
{selectedSpeciality &&
selectedSpeciality.map((el) => (
<Fragment key={el.value}>
<Grid item xs={6}>
<TextField
fullWidth
InputLabelProps={{
shrink: true
}}
value={el.enrollment}
onChange={(e) =>
handleChangeEnrollment(e.target.value, el.id)
}
label={`MATRÍCULA ${el.label.toUpperCase()}`}
/>
</Grid>
</Fragment>
))}
{console.log(selectedSpeciality)}
</Grid>
</Box>
</div>
</div>
);
};
export default FormAddProfessional;
a guy helped me with this code
import React, { useEffect, useState } from "react";
import _ from "lodash";
// const SeleccionClientes = "";
const items = [
{
client: "Microsoft",
idClient: 0,
idProjectType: 1,
projectType: "traditional",
title: "React Native App"
},
{
client: "Amazon",
idClient: 1,
idProjectType: 1,
projectType: "traditional",
title: "ServerSide OPS"
},
{
client: "KFC",
idClient: 2,
idProjectType: 4,
projectType: "traditional",
title: "QR Reader"
},
{
client: "KFC",
idClient: 2,
idProjectType: 1,
projectType: "traditional",
title: "React Native App"
},
{
client: "KFC",
idClient: 2,
idProjectType: 1,
projectType: "traditional",
title: "React KKL"
},
{
client: "PEICI",
idClient: 3,
idProjectType: 1,
projectType: "traditional",
title: "KuKluxKlan"
}
];
export default function ListView() {
const [list, setList] = useState(items);
const [idClient, setIdClient] = useState(2);
const displayProjectsForClient = idClient => {
return list.filter(item => item.idClient === idClient);
};
const displayedProjects = displayProjectsForClient(idClient);
// equivalent to componentDidMount()
useEffect(() => {
setList(displayedProjects);
}, []);
const updateFav = (val, ind) => {
const tempData = _.cloneDeep(list);
tempData[ind].fav = val;
setList(tempData);
};
const favItems = _.filter(list, item => item.fav);
const finalObject = { [new Date().toISOString()]: favItems };
return (
<div>
Selected Client: "KFC"
<br />
Add Favorite Projects:
{displayedProjects.map((item, index) => {
return (
<div
key={index}
style={{ margin: "5px", padding: "5px", background: "#D6D6D6" }}
>
<div>{item.title}</div>
{`Project ID ${item.idProjectType}`}
<input
type="checkbox"
value={item.fav}
onChange={e => updateFav(e.target.checked, index)}
/>
</div>
);
})}
<div>
Active projects (final object): <br />
{JSON.stringify(finalObject, null, 2)}
</div>
</div>
);
}
instead of input checkbox, i'm using the react-native-elements switch, but is not working, i'm assuming is due to a non existing fav inside the item object
this is my code
<FlatList
data={dataSource}
renderItem={({item, index}) => (
<ListItem
containerStyle={{backgroundColor: '#fafafa', width: wp('87.1%'), height: 64, alignItems: 'center', justifyContent: 'center', alignSelf: 'center', marginTop: hp('2.8%'), paddingHorizontal: 0}}
topDivider={false}
bottomDivider={true}
titleStyle={{
marginLeft: 0,
fontSize: rfv(16),
fontWeight: "normal",
fontStyle: "normal",
textAlign: "left",
color: "#707070"
}}
subtitleStyle={{
marginLeft: 0,
fontSize: rfv(14),
fontWeight: "normal",
fontStyle: "normal",
textAlign: "left",
color: "#c4c4c4"
}}
title={`${item.title}`}
subtitle={`ID ${item.idCliente}`}
switch={{
trackColor: { false: "#767577", true: "#81b0ff" },
thumbColor: item.fav == true ? "#1062cc" : "#f4f3f4",
ios_backgroundColor: "#9e9e9e",
value: item.fav == undefined ? false : true,
onValueChange: () => {e => console.log(updateFav(e.target.checked == undefined ? false : true, index))}
}}
/>
)}
/>
the idea is to list the projects, which is doing, but when i click on a switch, it creates a whole new object based on that "selection", problem is, the switches are getting to the original position immediately,
forgot to mention, this is the function
const updateFav = (value, index) => {
const tempData = _.cloneDeep(dataSource);
tempData[index].fav = value;
setDataSource(tempData);
};
const favItems = _.filter(dataSource, item => item.fav);
You are using a mixture of React (Html) and React native thats the problem. You will have to change your Switch like this for the function to work. And no need to check for true false as well.
switch={{
trackColor: { false: "#767577", true: "#81b0ff" },
thumbColor: item.fav == true ? "#1062cc" : "#f4f3f4",
ios_backgroundColor: "#9e9e9e",
value: item.fav,
onValueChange: () => {updateFav(!item.fav, index)}
}}