Antd Checkboxes deselect after re-rendering component - reactjs

I'm trying to create antd Checkbox.Group that consists of normal checkboxes as well as the "New Value" checkbox, selecting which would change the showForm state and result in showing input-fields.
I would like to be able to select both regular and hardcoded checkbox simultaneously. However, when I change the state of component which re-renders it, all checkboxes (including "New Value" one) automatically deselect.
Is there a way to prevent it?
antd version: ^4.22.7
checkboxes.tsx:
import {useCallback, useState} from "react";
import {CheckboxValueType} from "antd/lib/checkbox/Group";
import {Checkbox, Input} from "antd";
export interface CheckboxValuesModel {
name: string;
value: string;
}
const Checkboxes = () => {
const [showForm, setShowForm] = useState(false);
const toggleShowForm = useCallback((values: CheckboxValueType[]) => {
setShowForm(!!values.find(val => (val as unknown as CheckboxValuesModel).name === null));
}, []);
const checkboxValues: CheckboxValuesModel[] = [
{
name: 'A',
value: 'A'
},
{
name: 'B',
value: 'B'
},
]
return <>
<Checkbox.Group onChange={checkedValue => toggleShowForm(checkedValue)}>
{
checkboxValues.map(value => (
<Checkbox key={value.name} value={value}>
{value.name}
</Checkbox>
))
}
<Checkbox value={{name: null, value: null}}>
New Value
</Checkbox>
</Checkbox.Group>
{
showForm &&
<>
<Input name={'name'}></Input>
<Input name={'value'}></Input>
</>
}
</>
};
export default Checkboxes;
CodeSandbox link:
https://codesandbox.io/s/happy-water-npqxii

Related

Removing items in react-select with MultiValueContainer

I am using react-select to implement a multi-value drop down but using our internal UI component library to render the selected values in the input box. I am overriding the MultiValueContiner with our component. It renders fine, I can select items and they are added and rendered in the input box. The problem is with removing items. What can I access from the onClick handler of the component to remove it from the currently selected options? Do I simply need to add the currentValue & setCurrentValue state accessors to each menu option items and access through e.g. props.data.setCurrentValue()?
Custom MultiValueContainer
import { useState } from 'react';
import Select, { InputActionMeta, components, MultiValueGenericProps, MultiValue, ActionMeta } from 'react-select';
// import component from internal UI lib, dummy import here
import MyUIObject from './MyUIObject';
interface MenuOption {
value: string;
label: string;
}
export interface Props {
title: string;
items: MenuOption[];
}
const MyUIObjectValueContainer = (props: MultiValueGenericProps<MenuOption>) => {
return (
<components.MultiValueContainer {...props}>
<MyUIObject
text={props.data.label}
onClick={ (e) => {
e.stopPropagation();
e.preventDefault();
// HOW TO REMOVE FROM SELECTED OPTIONS ???
}}
/>
</components.MultiValueContainer>
);
};
function MyCustomMultiSelect(props: Props) {
const [inputValue, setInputValue] = useState('');
const [currentValue, setCurrentValue] = useState<MenuOption[]>([]);
function handleInputChange(newValue: string, actionMeta: InputActionMeta) {
if (actionMeta.action === 'input-change') {
setInputValue(newValue);
}
}
// clear manually typed search string from input
function handleOnBlur() {
setInputValue('');
}
function handleOnChange(newValue: MultiValue<MenuOption>, actionMeta: ActionMeta<MenuOption>) {
setCurrentValue( newValue as MenuOption[] );
}
return (
<Select
isMulti
isClearable
isSearchable
options={props.items}
closeMenuOnSelect={false}
onInputChange={handleInputChange}
inputValue={inputValue}
onBlur={handleOnBlur}
components={{ MultiValueContainer: MyUiObjectValueContainer }}
value={currentValue}
onChange={handleOnChange}
/>
);
}
export default MyCustomMultiSelect;
You haven't shared the code for your custom option component, so I'm assuming you built it correctly and made sure react-select's props are being spread into the custom component react-select docs.
In the case of multi select, the state you manage should be an array of selected options containing a label and an id properties. When you click on a selected option to remove it, react-select returns a new array of selected values with the option you clicked on filtered out. You should be able to just grab that returned array and set your selected option state I'm demoing in this simplified code:
import { useState } from "react";
import Select from "react-select";
export const options = [
{ label: "Option 1", value: 1 },
{ label: "Option 2", value: 2 },
{ label: "Option 3", value: 3 },
{ label: "Option 4", value: 4 },
{ label: "Option 5", value: 5 }
];
const App = () => {
const [value, setValue] = useState([]);
const handleChange = (e) => setValue(e);
return (
<Select
value={value}
options={options}
isMulti
onChange={handleChange}
closeMenuOnSelect={false}
/>
);
};
export default App;
You can have a look in this sandbox as well to see it working

React-select not displaying input when modifying value prop using state hooks

Ive been trying to make a dynamic input field(more input options appear on user input) with react-select, the input gets displayed when I'm not modifying value prop using state variables, but when I modify value prop using state hooks it is not displaying anything.
Here is the code snippet for without hooks which displays output just fine
import React,{useState} from "react"
import CreatableSelect from 'react-select/creatable';
export default function DynamicInput(){
const [val,setVal] = useState([])
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const handleAdd=()=>{
const tempVal = [...val,[]]
setVal(tempVal)
}
const handleDel=(indx)=>{
const deleteVal = [...val]
deleteVal.splice(indx,1);
setVal(deleteVal);
}
return (
<div>
<button onClick={()=>handleAdd()}>Add</button>
{val.map((data,indx)=>{
return(
<div key = {indx}>
<CreatableSelect isClearable options={options} placeholder="Placeholder" } />
<button onClick = {()=>handleDel(indx)}>X</button>
</div>
)
})
}
</div>
);
}
Now I tried to use hooks to handle the input hooks.
import React, { useState } from "react";
import CreatableSelect from "react-select/creatable";
export function DynamicInputwHooks() {
const [val, setVal] = useState([]);
const [selectedOp, setSelectedOp] = useState([]);
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
const handleAdd = () => {
const tempVal = [...val, []];
const tempSel = [...selectedOp, []];
setSelectedOp(tempSel);
setVal(tempVal);
};
const handleSelection = (v, indx) => {
const tempSel = [...selectedOp];
tempSel[indx] = v.value;
setSelectedOp(tempSel);
};
const handleDel = (indx) => {
const deleteVal = [...val];
const deletesel = [...selectedOp];
deleteVal.splice(indx, 1);
deletesel.splice(indx, 1);
setVal(deleteVal);
setSelectedOp(deletesel);
};
return (
<div>
<button onClick={() => handleAdd()}>Add</button>
{val.map((data, indx) => {
return (
<div key={indx}>
<CreatableSelect
isClearable
options={options}
placeholder={"Placeholder"}
value={selectedOp[indx]}
onChange={(e) => handleSelection(e, indx)}
/>
<button onClick={() => handleDel(indx)}>X</button>
</div>
);
})}
</div>
);
}
I also added an input box with the same value and it displays value accordingly.
(I am unable to embed code using sandbox but this is the link : https://codesandbox.io/s/frosty-darwin-s3ztee?file=/src/App.js)
Upon using inspect element I found that when not using handling value there is an additional div as compared to when modifying value.
When not handling value prop
The single value div
when handling value prop
No single value div gets created
I cannot use useRef as there can be multiple inputs.
any help how to solve this would be appreciated thanks.
Ok so after some more searching I found this sandbox example that helps solve the problem
https://codesandbox.io/s/react-select-set-value-example-d21pt?file=/src/App.js
while this works for react-select but using it for react-select creatable requires appending to the options based on isNew prop of input when creating a new option.

React Button Multi-Select, strange style behaviour

I am trying to create a simple button multi-select in React but I'm currently getting unexpected behaviour. I'd like users to be able to toggle multiple buttons and have them colourise accordingly, however the buttons seem to act a bit randomly.
I have the following class
export default function App() {
const [value, setValue] = useState([]);
const [listButtons, setListButtons] = useState([]);
const BUTTONS = [
{ id: 123, title: 'button1' },
{ id: 456, title: 'button2' },
{ id: 789, title: 'button3' },
];
const handleButton = (button) => {
if (value.includes(button)) {
setValue(value.filter((el) => el !== button));
} else {
let tmp = value;
tmp.push(button);
setValue(tmp);
}
console.log(value);
};
const buttonList = () => {
setListButtons(
BUTTONS.map((bt) => (
<button
key={bt.id}
onClick={() => handleButton(bt.id)}
className={value.includes(bt.id) ? 'buttonPressed' : 'button'}
>
{bt.title}
</button>
))
);
};
useEffect(() => {
buttonList();
}, [value]);
return (
<div>
<h1>Hello StackBlitz!</h1>
<div>{listButtons}</div>
</div>
);
}
If you select all 3 buttons then select 1 more button the css will change.
I am trying to use these as buttons as toggle switches.
I have an example running #
Stackblitz
Any help is much appreciated.
Thanks
I think that what you want to achieve is way simpler:
You just need to store the current ID of the selected button.
Never store an array of JSX elements inside a state. It is not how react works. Decouple, only store the info. React component is always a consequence of a pattern / data, never a source.
You only need to store the necessary information, aka the button id.
Information that doesn't belong to the state of the component should be moved outside. In this case, BUTTONS shouldn't be inside your <App>.
Working code:
import React, { useState } from 'react';
import './style.css';
const BUTTONS = [
{ id: 123, title: 'button1', selected: false },
{ id: 456, title: 'button2', selected: false },
{ id: 789, title: 'button3', selected: false },
];
export default function App() {
const [buttons, setButtons] = useState(BUTTONS);
const handleButton = (buttonId) => {
const newButtons = buttons.map((btn) => {
if (btn.id !== buttonId) return btn;
btn.selected = !btn.selected;
return btn;
});
setButtons(newButtons);
};
return (
<div>
<h1>Hello StackBlitz!</h1>
<div>
{buttons.map((bt) => (
<button
key={bt.id}
onClick={() => handleButton(bt.id)}
className={bt.selected ? 'buttonPressed' : 'button'}
>
{bt.title}
</button>
))}
</div>
</div>
);
}
I hope it helps.
Edit: the BUTTONS array was modified to add a selected property. Now several buttons can be selected at the same time.

How to get specific value when changing Autocomplete component of Material UI

I am trying to implement the autocomplete component of the ui material, I would like that when there is a change in the selection, I would capture the ID of the selected team.
As below, i'm getting the team name, how would you get the ID?
Complete code: .
import React, { useCallback } from 'react';
import { Field } from 'formik';
import MuiTextField from '#material-ui/core/TextField';
import {
Autocomplete,
AutocompleteRenderInputParams,
} from 'formik-material-ui-lab';
const teams = [
{ id: 1, name: 'Barcelona' },
{ id: 2, name: 'Real Madrid'}
];
const Teams: React.FC = () => {
const handleShowId = useCallback((event, value) => {
alert(value)
},[])
return (
<Field
name="teams"
component={Autocomplete}
options={teams}
size="small"
getOptionLabel={(option: any) => option.name}
onInputChange={handleShowId}
renderInput={(params: AutocompleteRenderInputParams) => (
<MuiTextField
{...params}
label="Select"
variant="outlined"
/>
)}
/>
)
};
export default Teams;
onInputChange doesn't return the id. You can get the id though by targeting the selected option and look upon your array of options.
const handleShowId = React.useCallback((event) => {
const selectedId = event.target.id.split('option-').pop();
alert(teams[selectedId].id);
}, []);

React Hook Form Register Different Forms With Same Field Names

I have a material ui stepper in which there are multiple forms using react-hook-form. When I change between steps, I would expect a new useForm hook to create new register functions that would register new form fields, but when I switch between steps, the second form has the data from the first. I've seen at least one question where someone was trying to create two forms on the same page within the same component but in this case I am trying to create two unique forms within different steps using different instances of a component. It seems like react-hook-form is somehow not updating the useForm hook or is recycling the form fields added to the first register call.
Why isn't react-hook-form using a new register function to register form fields to a new useForm hook? Or at least, why isn't a new useForm hook being created between steps?
DynamicForm component. There are two of these components (one for each step in the stepper).
import { Button, Grid } from "#material-ui/core";
import React from "react";
import { useForm } from "react-hook-form";
import { buttonStyles } from "../../../styles/buttonStyles";
import AppCard from "../../shared/AppCard";
import { componentsMap } from "../../shared/form";
export const DynamicForm = (props) => {
const buttonClasses = buttonStyles();
const { defaultValues = {} } = props;
const { handleSubmit, register } = useForm({ defaultValues });
const onSubmit = (userData) => {
props.handleSubmit(userData);
};
return (
<form
id={props.formName}
name={props.formName}
onSubmit={handleSubmit((data) => onSubmit(data))}
>
<AppCard
headline={props.headline}
actionButton={
props.actionButtonText && (
<Button className={buttonClasses.outlined} type="submit">
{props.actionButtonText}
</Button>
)
}
>
<Grid container spacing={2}>
{props.formFields.map((config) => {
const FormComponent = componentsMap.get(config.component);
return (
<Grid key={`form-field-${config.config.name}`} item xs={12}>
<FormComponent {...config.config} register={register} />
</Grid>
);
})}
</Grid>
</AppCard>
</form>
);
};
N.B. The images are the same because the forms will contain the same information, i.e. the same form fields by name.
Entry for first form:
Entry for the second form:
Each form is created with a config like this:
{
component: DynamicForm,
label: "Stepper Label",
config: {
headline: "Form 1",
actionButtonText: "Next",
formName: 'form-name',
defaultValues: defaultConfigObject,
formFields: [
{
component: "AppTextInput",
config: {
label: "Field 1",
name: "field_1",
},
},
{
component: "AppTextInput",
config: {
label: "Field2",
name: "field_2",
},
},
{
component: "AppTextInput",
config: {
label: "Field3",
name: "field_3",
},
},
{
component: "AppTextInput",
config: {
label: "Field4",
name: "field4",
},
},
],
handleSubmit: (formData) => console.log(formData),
},
},
And the active component in the steps is handled like:
import { Button, createStyles, makeStyles, Theme } from "#material-ui/core";
import React, { useContext, useEffect, useState } from "react";
import { StepperContext } from "./StepperProvider";
const useStyles = makeStyles((theme: Theme) =>
createStyles({
buttonsContainer: {
margin: theme.spacing(2),
},
buttons: {
display: "flex",
justifyContent: "space-between",
},
})
);
export const StepPanel = (props) => {
const { activeStep, steps, handleBack, handleNext, isFinalStep } = useContext(
StepperContext
);
const [activeComponent, setActiveComponent] = useState(steps[activeStep]);
const classes = useStyles();
useEffect(() => {
setActiveComponent(steps[activeStep]);
}, [activeStep]);
return (
<div>
<activeComponent.component {...activeComponent.config} />
{
isFinalStep ? (
<div className={classes.buttonsContainer}>
<div className={classes.buttons}>
<Button disabled={activeStep === 0} onClick={handleBack}>
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={props.finishFunction}
>
Finish And Submit
</Button>
</div>
</div>
)
:
null
}
</div>
);
};
From your image, every form looks the same. You should try providing a unique key value to your component so React know that each form is different. In this case it can be the step number for example:
<activeComponent.component {...props} key='form-step-1'>

Resources