How can I implement not only one but multi setting toggles? - reactjs

I use Shopify Polaris's setting toggle.https://polaris.shopify.com/components/actions/setting-toggle#navigation
And I want to implement not only one but multi setting toggles.But I don't want to always duplicate same handleToggle() and values(contentStatus, textStatus) like below the sandbox A,B,C...
import React, { useCallback, useState } from "react";
import { SettingToggle, TextStyle } from "#shopify/polaris";
export default function SettingToggleExample() {
const [activeA, setActiveA] = useState(false);
const [activeB, setActiveB] = useState(false);
const handleToggleA = useCallback(() => setActiveA((active) => !active), []);
const handleToggleB = useCallback(() => setActiveB((active) => !active), []);
const contentStatusA = activeA ? "Deactivate" : "Activate";
const contentStatusB = activeB ? "Deactivate" : "Activate";
const textStatusA = activeA ? "activated" : "deactivated";
const textStatusB = activeB ? "activated" : "deactivated";
const useHandleToggle = (active, setActive) => {
const handleToggle = useCallback(() => setActive((active) => !active), []);
const contentStatus = active ? "Disconnect" : "Connect";
const textStatus = active ? "connected" : "disconnected";
handleToggle();
return [contentStatus, textStatus];
};
useHandleToggle(activeA, setActiveA);
return (
<>
<SettingToggle
action={{
content: contentStatusA,
onAction: handleToggleA
}}
enabled={activeA}
>
This setting is <TextStyle variation="strong">{textStatusA}</TextStyle>.
</SettingToggle>
<SettingToggle
action={{
content: contentStatusB,
onAction: handleToggleB
}}
enabled={activeB}
>
This setting is <TextStyle variation="strong">{textStatusB}</TextStyle>.
</SettingToggle>
</>
);
}
https://codesandbox.io/s/vigorous-pine-k0dpib?file=/App.js
So I thought I can use a custom hook. But it's not working. So it would be helpful if you give me some advice.

Using simple Booleans for each toggle
If you combine your active state objects into a single array, then you can update as many settings as you would like dynamically. Here's an example of what that might look like:
import React, { useCallback, useState } from "react";
import { SettingToggle, TextStyle } from "#shopify/polaris";
export default function SettingToggleExample() {
// define stateful array of size equal to number of toggles
const [active, setActive] = useState(Array(2).fill(false));
const handleToggle = useCallback((i) => {
// toggle the boolean at index, i
setActive(prev => [...prev.slice(0,i), !prev[i], ...prev.slice(i+1)])
}, []);
return (
<>
{activeStatuses.map((isActive, index) =>
<SettingToggle
action={{
content: isActive ? "Deactivate" : "Activate",
onAction: () => handleToggle(index)
}}
enabled={isActive}
>
This setting is <TextStyle variation="strong">{isActive ? "activated" : "deactivated"}</TextStyle>.
</SettingToggle>
}
</>
);
}
Of course, you will likely want to add a label to each of these going forward, so it may be better to define a defaultState object outside the function scope and replace the Array(2).fill(false) with it. Then you can have a string label property for each toggle in addition to a boolean active property which can be added next to each toggle in the .map(...).
With labels added for each toggle
Per your follow up, here is the implementation also found in the CodeSandbox for a state with labels for each toggle (including here on the answer to protect against link decay):
import React, { useCallback, useState } from "react";
import { SettingToggle, TextStyle } from "#shopify/polaris";
const defaultState = [
{
isActive: false,
label: "A"
},
{
isActive: false,
label: "B"
},
{
isActive: false,
label: "C"
}
];
export default function SettingToggleExample() {
const [active, setActive] = useState(defaultState);
const handleToggle = useCallback((i) => {
// toggle the boolean at index, i
setActive((prev) => [
...prev.slice(0, i),
{ ...prev[i], isActive: !prev[i].isActive },
...prev.slice(i + 1)
]);
}, []);
return (
<div style={{ height: "100vh" }}>
{active?.map(({ isActive, label }, index) => (
<SettingToggle
action={{
content: isActive ? "Deactivate" : "Activate",
onAction: () => handleToggle(index)
}}
enabled={isActive}
key={index}
>
This {label} is 
<TextStyle variation="strong">
{isActive ? "activated" : "deactivated"}
</TextStyle>
.
</SettingToggle>
))}
</div>
);
}

My first attempt to refactor would use a parameter on the common handler
const handleToggle = useCallback((which) => {
which === 'A' ? setActiveA((activeA) => !activeA)
: setActiveB((activeB) => !activeB)
},[])
...
<SettingToggle
action={{
content: contentStatusA,
onAction: () => handleToggle('A')
}}
enabled={activeA}
>
It functions, but feels a bit naïve. For something more React-ish, a reducer might be the way to go.
With a reducer
This seems cleaner, and is definitely more extensible if you need more toggles.
function reducer(state, action) {
switch (action.type) {
case "toggleA":
const newValueA = !state.activeA;
return {
...state,
activeA: newValueA,
contentStatusA: newValueA ? "Deactivate" : "Activate",
textStatusA: newValueA ? "activated" : "deactivated"
};
case "toggleB":
const newValueB = !state.activeB;
return {
...state,
activeB: newValueB,
contentStatusB: newValueB ? "Deactivate" : "Activate",
textStatusB: newValueB ? "activated" : "deactivated"
};
default:
throw new Error();
}
}
const initialState = {
activeA: false,
activeB: false,
contentStatusA: "Activate",
contentStatusB: "Activate",
textStatusA: "deactivated",
textStatusB: "deactivated"
};
export default function SettingToggleExample() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
<SettingToggle
action={{
content: state.contentStatusA,
onAction: () => dispatch({type: 'toggleA'})
}}
enabled={state.activeA}
>
This setting is <TextStyle variation="strong">{state.textStatusA}</TextStyle>.
</SettingToggle>
<SettingToggle
action={{
content: state.contentStatusB,
onAction: () => dispatch({type: 'toggleA'})
}}
enabled={state.activeB}
>
This setting is <TextStyle variation="strong">{state.textStatusB}</TextStyle>.
</SettingToggle>
</>
);
}
With a wrapper component
A child component can eliminate the 'A' and 'B' suffixes
function reducer(state, action) {
switch (action.type) {
case "toggle":
const newValue = !state.active;
return {
...state,
active: newValue,
contentStatus: newValue ? "Deactivate" : "Activate",
textStatus: newValue ? "activated" : "deactivated"
};
default:
throw new Error();
}
}
const initialState = {
active: false,
contentStatus: "Activate",
textStatus: "deactivated",
};
const ToggleWrapper = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<SettingToggle
action={{
content: state.contentStatus,
onAction: () => dispatch({ type: "toggle" })
}}
enabled={state.active}
>
This setting is <TextStyle variation="strong">{state.textStatus}</TextStyle>.
</SettingToggle>
)
}
export default function SettingToggleExample() {
return (
<>
<ToggleWrapper />
<ToggleWrapper />
</>
);
}

Related

MUI Snackbar Rerenders Again When Store Gets Updated

I am using MUI Snackbar in my root component (using STORE) and it appeared more than once because when store updated, the component gets re-rendered again
Snackbar Component:
export type BaseLayoutProps = {
children: ReactNode;
};
const Toast: FC<BaseLayoutProps> = ({ children }) => {
const [state,] = useSetupsStore();
const { toastProps } = state;
const [open, setOpen] = useState(toastProps?.toastState);
useEffect(() => {
if (toastProps) {
setOpen(toastProps.toastState);
}
}, [toastProps]);
const handleClose = (
event: React.SyntheticEvent | Event,
reason?: string
) => {
if (reason === "clickaway") {
return;
}
setOpen(false);
};
return (
<>
<Snackbar
theme={unityTheme}
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
autoHideDuration={
toastProps?.toastLength ? toastProps.toastLength : 5000
}
variant={toastProps?.variant}
open={open}
onClose={handleClose as any}
message={toastProps?.toastMessage ? toastProps?.toastMessage : "Testing"}
TransitionComponent={(props) => <Slide {...props} direction="up" />}
/>
{children}
</>
)
}
export default Toast;
SnackBar Action:
export const setToast = (toastProps: IToast): StoreActionType => {
if (toastProps?.toastState) {
return { type: ActionTypes.SET_TOAST, payload: toastProps };
}
};
Snackbar Reducer
export const ToastReducer = (
state: IToast,
action: StoreActionType
): IToast => {
switch (action.type) {
case ActionTypes.SET_TOAST:
return {
...state,
toastState: (action.payload as IToast).toastState,
variant: (action.payload as IToast).variant,
toastMessage: (action.payload as IToast).toastMessage,
// toastLength: (action.payload as IToast).toastLength,
}
default:
return state
}
};
Dispatch Code:
dispatch(
setToast({
toastMessage: ToastMessages.Record_Added_Success,
toastState: true,
})
);
I'm 100% sure that it is dispatching only once but when another api get called(store get updated) it again comes to my reducer and root component get re-rendered again due to which it appeared twice. I have also return null in default case in reducer like this:
export const ToastReducer = (
state: IToast,
action: StoreActionType
): IToast => {
switch (action.type) {
case ActionTypes.SET_TOAST:
console.log("inside case",action);
return {
...state,
toastState: (action.payload as IToast).toastState,
variant: (action.payload as IToast).variant,
toastMessage: (action.payload as IToast).toastMessage,
}
default:
return null
}
In above case Snackbar appeared only once for a milisecond & then disappeared again
How to resolve this?

Infinite call renderCell in React

I'm using function component to create a MUI dataGrid, and trying to add a button in a column, and I have a onRowClick function to open a side pane when user clicking row. The problem is, once I click row, react will report error:
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
Here is the code:
const openViewPane = (params: GridRowParams, e): void => {
setRightSlidePlaneContent(
<ViewAccountPane
close={closeForm}
params={params}
/>,
);
setRightSlidePlaneOpen(true);
};
const formatDates = (columns): GridColDef[] => {
return columns;
};
const addTooltipsToData = (columns: GridColDef[]): GridColDef[] => {
console.log('render tool bar called');
return columns.map((column) => {
const { description, field, headerName } = column;
console.log('inside map');
if (field === ID) {
console.log('直接return');
return column;
}
return {
...column,
renderCell: (): JSX.Element => {
console.log('render run');
return (
<Tooltip arrow title={description || ''} >
<span className={classes.headerCell}>{headerName}</span>
</Tooltip>
);
},
};
});
};
const formatColumns = (columns: GridColDef[]): GridColDef[] => {
const dateFormatted = formatDates(columns);
return addTooltipsToData(dateFormatted);
};
console.log('generic table rendered');
return (
<MuiThemeProvider theme={theme}>
<DataGrid
columns={formatColumns(columns)}
rows={rows}
autoHeight
className={classes.table}
components={{
Toolbar: CustomToolbar,
}}
density={GridDensityTypes.Compact}
filterMode={tableMode}
hideFooterSelectedRowCount
loading={loading}
onFilterModelChange={handleFilterChange}
onSortModelChange={handleSortChange}
sortModel={sortModel}
sortingMode={tableMode}
onRowClick={openViewPane}
/>
</MuiThemeProvider>
);
However, if I change the renderCell to renderHeader, it will work fine.
setRightSlidePlaneContent
setRightSlidePlaneOpen
Above are two state passed by parent component in props. it will open a slide pane.
After I comment setRightSliePlaneOpen, it will work well. But no slide pane show.
Please help me slove it. Or do you know how can I add a button in column not using renderCell?
const PageFrame: FC<IProps> = (props: IProps) => {
const classes = useStyles();
const dispatch = useAppDispatch();
const { Component, userInfo } = props;
const [navBarOpen, setNavBarOpen] = useState(false);
const [rightSlidePlaneOpen, setRightSlidePlaneOpen] = useState(false);
const [rightSlidePlaneContent, setRightSlidePlaneContent] = useState(
<Fragment></Fragment>,
);
const [rightSlidePlaneWidthLarge, setRightSlidePlaneWidthLarge] = useState(
false,
);
useEffect(() => {
dispatch({
type: `${GET_USER_LOGIN_INFO}_${REQUEST}`,
payload: {
empId: userInfo.empId,
auth: { domain: 'GENERAL_USER', actionType: 'GENERAL_USER', action: 'VIEW', empId: userInfo.empId},
},
meta: { remote: true },
});
}, []);
return (
<div className={classes.root}>
<HeaderBar
navBarOpen={navBarOpen}
toggleNavBarOpen={setNavBarOpen}
/>
<NavigationBar open={navBarOpen} toggleOpen={setNavBarOpen} />
<Component
setRightSlidePlaneContent={setRightSlidePlaneContent}
setRightSlidePlaneOpen={setRightSlidePlaneOpen}
setRightSlidePlaneWidthLarge={setRightSlidePlaneWidthLarge}
/>
<PersistentDrawerRight
content={rightSlidePlaneContent}
open={rightSlidePlaneOpen}
rspLarge={rightSlidePlaneWidthLarge}
/>
</div>
);
};
export default PageFrame;
The component that calls setRightSidePlaneOpen
interface IProps {
setRightSlidePlaneContent: React.Dispatch<React.SetStateAction<JSX.Element>>;
setRightSlidePlaneOpen: React.Dispatch<React.SetStateAction<boolean>>;
setRightSlidePlaneWidthLarge: React.Dispatch<SetStateAction<boolean>>;
}
const TagDashboard = (props: IProps): JSX.Element => {
const { setRightSlidePlaneContent, setRightSlidePlaneOpen, setRightSlidePlaneWidthLarge } = props;
const employeeId = useAppSelector((store) => store.userInfo.info.employeeNumber);
const rows = useAppSelector((state) => state.tag.rows);
const accountId = useAppSelector(store => store.userInfo.accountId);
const updateContent = useAppSelector(state => state.tag.updateContent);
const numOfUpdates = useAppSelector(state => state.tag.numOfUpdates);
const dispatch = useAppDispatch();
const closeAddForm = (): void => {
setRightSlidePlaneContent(<Fragment />);
setRightSlidePlaneOpen(false);
};
const openAddForm = (): void => {
setRightSlidePlaneContent(
<AddForm
category={'tag'}
close={closeAddForm}
title={ADD_FORM_TITLE}
createFunction={createTag}
/>);
setRightSlidePlaneOpen(true);
};
const closeForm = (): void => {
setRightSlidePlaneContent(<Fragment />);
setRightSlidePlaneOpen(false);
setRightSlidePlaneWidthLarge(false);
};
const openViewPane = (params: GridRowParams, e): void => {
setRightSlidePlaneContent(
<ViewAccountPane
close={closeForm}
params={params}
/>,
);
setRightSlidePlaneOpen(true);
setRightSlidePlaneWidthLarge(true);
};
// to the RSP.
return (
<GenericDashboard
addFunction={openAddForm}
description={DESCRIPTION}
title={TITLE}
columns={columns}
handleRowClick={openViewPane}
rows={rows}
numOfUpdates={numOfUpdates}
updateContent={updateContent}
/>
);
};
This is the component of the right slide pane
const { content, open, rspLarge } = props;
const classes = useStyles();
const drawerClass = rspLarge ? classes.drawerLarge : classes.drawer;
const drawerPaperClass = rspLarge ? classes.drawerPaperLarge : classes.drawerPaper;
return (
<div className={classes.root}>
<CssBaseline />
<Drawer
className={drawerClass}
variant='temporary'
anchor='right'
open={open}
classes={{
paper: drawerPaperClass,
}}
>
<Fragment>{content}</Fragment>
</Drawer>
</div>
);

Find element has className in enzyme not found with renderoption autocompleted material

I'm testing react component use enzyme and jest test. I'm try use find method in enzyme but it not found, i'm sure this element have been render because when I print actionClass const it return value "ts-cbb-item".
I have a combobox component:
/* eslint-disable no-use-before-define */
import Autocomplete from '#material-ui/lab/Autocomplete';
import PropTypes from 'prop-types';
import React, { useState, useRef } from 'react';
import './index.scss';
import InputCombobox from './input-combobox';
const ComboBox = (props) => {
const {
loading,
options,
onDataBinding,
onChange,
customRenderItem,
placeholder,
renderStartAdornment,
closeIcon,
disabled,
customGetOptionLabel,
onInputChange,
style,
clearOnBlur = false,
defaultValue,
...rest
} = props;
const currentSearch = useRef();
const [currentOption, setOption] = useState(null);
const [isInput, setIsInput] = useState(false);
const handleInputChange = (_, value, reason) => {
const isReasonInput = reason === 'input';
if (isReasonInput) {
setIsInput(false);
if (onInputChange)
onInputChange(value);
}
currentSearch.current = value;
if (value?.length < 3) return;
if (isReasonInput) onDataBinding(value);
}
const handleChangeOpt = (opt) => {
setIsInput(true);
if (onChange) onChange(opt);
}
return (
<Autocomplete
clearOnBlur={clearOnBlur}
disabled={disabled}
closeIcon={closeIcon}
className="ts-combobox"
options={options}
loading={loading}
onInputChange={handleInputChange}
defaultValue={defaultValue}
getOptionLabel={(option) => customGetOptionLabel
? customGetOptionLabel(option)
: option.label}
getOptionSelected={option => {
if (!currentOption || !currentOption.value) return false;
return option.value === currentOption.value;
}}
style={style ? style : { width: '100%' }}
renderOption={(option, state) => {
const actionClass = state?.selected ? "ts-ccb-item active" : "ts-ccb-item";
console.log('class:', actionClass);
return <div
onClick={() => {
setOption(option);
handleChangeOpt(option);
}}
className={actionClass}>
{ customRenderItem
? customRenderItem(option, currentSearch)
: option.label }
</div>
}}
);
}
export default ComboBox;
This is my test :
let initProps = {
loading: false,
options: [],
onDataBinding: () => {},
onChange: () => {},
customRenderItem: () => {},
renderStartAdornment: () => {},
closeIcon: null,
disabled: false,
customGetOptionLabel: () => {},
onInputChange: () => {},
style: null,
clearOnBlur: false,
placeholder: '',
defaultValue: null
}
const options = [
{
label: 'Cristiano Ronaldo',
value: 'Portugal'
},
{
label : 'Leo Messi',
value : 'Argentina'
},
{
label : 'Jesse Lingard',
value : 'England'
}
]
const event = {
preventDefault() {},
}
const onInputChangeMockFn = jest.fn((value) => value);
const onDataBindingMockFn = jest.fn( (value) => value? true: false);
const renderStartAdornmentMockFn = jest.fn((option) => option ? option.value : null );
const customGetOptionLabelMockFn = jest.fn((option) => option? option.label : null)
const renderInputParams = {
id: '',
disabled: false,
fullWidth: true,
size: 'small',
InputLabelProps: {},
InputProps: {},
inputProps: {}
}
it("Test_Comobox_With_RenderInput_Active(RenderStartAdornment_Have_Value)", () => {
initProps.renderStartAdornment = renderStartAdornmentMockFn;
initProps.customGetOptionLabel = customGetOptionLabelMockFn;
initProps.options = options;
const wrapper = mount(
<ComboBox {...initProps} />
);
const autoCompleted = wrapper.find(Autocomplete);
autoCompleted.props().renderOption(options[1], autoCompletedRenderOptionState);
autoCompleted.props().renderInput(renderInputParams);
expect(autoCompleted.find('div .ts-cbb-item')).toHaveLength(1);
const inputCombobox = wrapper.find(InputCombobox);
expect(inputCombobox.props().renderStartAdornment).toBeUndefined();
})
How can I find exactly element div has ClassName 'ts-cbb-item' in this case?

How to add a function in const Target = props => {

How do I add a function to connect to one of my components onChange? Creating a function like this returns an error code of 'cardActionResponse' is not defined.
What the benefit of using a const class like this?
const Target = props => {
const { markAsDone } = useContext(ItemContext);
const [{ isOver }, drop] = useDrop({
accept: 'Item',
drop: (item, monitor) => console.log(item),
collect: monitor => ({
isOver: !!monitor.isOver()
})
})
//Cannot do this. How else can I make a function to connect to CreateVideoCard?
cardActionResponse = (event) => {
console.log(event);
}
return (
<div className="target top80 right30" ref={drop} style={{ backgroundColor: isOver ? 'black' : '' }} >
<TitleDescription class="z1"/>
<div class="right10 left10">
<CreateVideoCard onChange={this.cardActionResponse} />
<CreateDescriptionCard></CreateDescriptionCard>
<CreateAudioCard></CreateAudioCard>
<CreateTermsCard></CreateTermsCard>
</div>
</div>
);
};
export default Target;
Functional components don't have it's own context (this), so you should simply use const variable.
Please use
const cardActionResponse = (event) => {
console.log(event);
}
and then
<CreateVideoCard onChange={cardActionResponse} />

Making a separated component disappear with useReducer

I'm currently learning the React Hooks feature so I created a small experiment where an invisible(unmounted) box would appear if the button is clicked; if the box is visible and you click on anywhere on the page except the box, the box would disappear. I'm struggling making the box disappear and I don't know what's causing the bug.
Initial state and the reducer:
const initialState = { visible: false };
const reducer = (state, action) => {
switch (action.type) {
case 'show':
return { visible: true };
case 'hide':
return { visible: false };
default:
return state;
}
};
The Box component:
function Box() {
const [state, dispatch] = useReducer(reducer, initialState);
const boxElement = useRef(null);
const boxStyle = {
width: '200px',
height: '200px',
background: 'blue'
};
function hideBox(e) {
if(!boxElement.current.contains(e.target)) {
dispatch({ type: 'hide' });
}
}
useEffect(() => {
window.addEventListener('click', hideBox);
return () => {
window.removeEventListener('click', hideBox);
}
});
return <div style={boxStyle} ref={boxElement} />
}
Main:
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function showBox() {
dispatch({ type: 'show' });
}
return (
<section>
{ state.visible && <Box /> }
<button onClick={showBox}>Show box</button>
</section>
)
}
You are using two instances of useReducer whereas you only need to have one at the App component level and pass dispatch as a prop to Box otherwise you would only be updating the state that is used by the useReducer in Box and not the state in App component
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function showBox() {
dispatch({ type: 'show' });
}
return (
<section>
{ state.visible && <Box dispatch={dispatch}/> }
<button onClick={showBox}>Show box</button>
</section>
)
}
Box.js
function Box({dispatch}) {
const boxElement = useRef(null);
const boxStyle = {
width: '200px',
height: '200px',
background: 'blue'
};
function hideBox(e) {
if(!boxElement.current.contains(e.target)) {
dispatch({ type: 'hide' });
}
}
useEffect(() => {
window.addEventListener('click', hideBox);
return () => {
window.removeEventListener('click', hideBox);
}
});
return <div style={boxStyle} ref={boxElement} />
}
Working demo

Resources