Material Table Detail Panel not re-rendering on state change - javascript

I'm having issues getting the Detail Panel of Material Table to re-render when there is a change to the tab selection of a Material-UI tab component. What I'm expecting to happen is when I select the second tab in the tab list, the styling and component should re-render to reflect that in the DOM. As of right now that isn't happening. The value property is being updated, but the DOM is never being re-rendered from the value change. The value property I'm passing to the handleChange function is an index. So for 3 tabs, there would be 3 different values (0, 1, 2)
You can see from this example , when you click a subsequent tab in the AppBar, the state is updated and changed automatically. I'm able to effectively change the 'value' property by clicking a different tab, but the Detail Panel is never re-rendered and the first tab is always selected.
This PR had a similar issue but I wasn't able to get any of the answers to work for my need.
import AppBar from '#material-ui/core/AppBar'
import Tabs from '#material-ui/core/Tabs'
import Tab from '#material-ui/core/Tab'
function TableComponent(props) {
const [value, setValue] = React.useState(0)
const handleChange = (event, newValue) => {
setValue(newValue)
}
function getVersionsTabs (rowData) {
const versions = Object.keys(rowData.versions)
var versionList = versions.map(function (name, index) {
const version = rowData.versions[name]
return <Tab key={index} label={version.versionAlias} />
})
return versionList
}
return (
<MaterialTable
...otherProps
detailPanel={
rowData => {
return (
<div>
<AppBar position='static' color='default'>
<Tabs value={value} onChange={handleChange} indicatorColor='primary' textColor='primary'>
{getVersionsTabs(rowData)}
</Tabs>
</AppBar>
</div>
)
}
/>
)
}
Any help is greatly appreciated!

Related

HTML changes are not saved when a checkbox is set and the page is changed in React + Bootstrap

I have an array with several "question" elements, each of them with a structure similar to this:
<><div className="row"><div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"><span>Question 1</span></div><div className="col-3 col-md-1 col-lg-1 col-xl-1"><div className="form-check"><input id="formCheck-1" className="form-check-input" type="checkbox" /><label className="form-check-label" for="formCheck-1">Yes</label></div></div><div className="col-3 col-md-1 col-lg-1 col-xl-1"><div className="form-check"><input id="formCheck-2" className="form-check-input" type="checkbox" /><label className="form-check-label" for="formCheck-2">No</label></div></div></div></>,
In order to give each element a bit of keyed structure, I store each array element in a helper component. The HTML of the questions is simply stored in "element". Simple:
const ElementoPaginacion = ({element}) =>{
return(
element
)
}
Since there can be many of these elements in this array, they are displayed with pagination. The displayed page is calculated (apparently correctly, using a simple calculation). The code snippet that calculates and displays it is as follows:
<>
{
//Calculate init index (it depends ont the current page) to show the questions, and the number of elements to show (its rangePages)
fullList.slice(currentPage * rangePages, (currentPage * rangePages) + rangePages).map((current) => (
<React.Fragment key={current.key}>
{current}
</React.Fragment>
))
}
What happens is that, when a change is made to that HTML by the user (for example, checking a checkbox), when changing the page, that change is NOT saved, if it is redrawed (for example, changing the page and returning to the same page afterwards). I am attaching images to see how it works:
We can see how we make changes to the questions on page 0, we change to page 1, and when we return to page 0 again, the changes (check ckeckboxes) have not been saved.
That could be happening?
------------- EDIT -------------
Okay. Right now, the idea is to save changes to any portion of HTML that is passed to us, be it a question with checkbox responses, or a radiobutton.
The problem: if we don't know what content is going to pass, what we have to save is all the content in html. Now, how can we save any HTML content that has been modified? I've tried creating this helper component, which wraps the HTML content passed to it inside a "div", but when clicked, how can I retrieve the new HTML content to reassign (ie the "newData" parameter)?
const ElementoPaginacion = ({element}) =>{
const [content, saveElement] = useState(element);
const saveData = (newData) =>{
saveElement(newData);
}
return(
<div onChange={saveData}>
{element}
</div>
)
}
Are you using a backend database? If not, the changes are stored in memory and will be lost each time you change the page.
You can use the useState hook to prevent the state of the forms from being lost each time the element is dismounted. Then the user can submit the state in its entirety after answering the questions.
Example:
import { useState } from 'react';
import { Button } from '#mui/material';
import { Checkbox } from '#mui/material';
function App() {
const [checkBoxIsMounted, setCheckBoxIsMounted] = useState(false);
const handleClick = () => {
setCheckBoxIsMounted(!checkBoxIsMounted)
}
return (
<>
<Button onClick={handleClick}>Mount Checkbox</Button>
{checkBoxIsMounted && <Checkbox />}
</>
);
}
export default App;
Note, I'm using MUI instead of Bootstrap, but the underlying principle is the same.
The above code snippet produces the following behavior:
If we add state to the checkbox, React will maintain the state in memory even after the component is dismounted:
import { useState } from 'react';
import { Button } from '#mui/material';
import { Checkbox } from '#mui/material';
function App() {
const [checkBoxIsMounted, setCheckBoxIsMounted] = useState(false);
const [checked, setChecked] = useState(false);
const handleClick = () => {
setCheckBoxIsMounted(!checkBoxIsMounted)
}
const handleChange = () => {
setChecked(!checked)
}
return (
<>
<Button onClick={handleClick}>Mount Checkbox</Button>
{checkBoxIsMounted && <Checkbox onChange={handleChange} checked={checked} />}
</>
);
}
export default App;
This modified snippet produces this behavior:

React: MaterialUI Select Component doesn't show passed values a prop

I have this FormControl element with Select that accepts an array of options that is being used for MenuItem options and also a value as props and this component looks like this:
const TaxonomySelector = (props) => {
const { isDisabled, taxonomies, selectedTaxonomy, handleTaxonomyChange } = props;
return (
<Grid item xs={12}>
{console.log(selectedTaxonomy)}
{console.log(taxonomies)}
<FormControl disabled={isDisabled} fullWidth>
<InputLabel>Таксономия</InputLabel>
<Select
value={selectedTaxonomy || ''}
onChange={handleTaxonomyChange}>
{Object.values(taxonomies).map((taxonomy) => (
<MenuItem key={taxonomy.id} name={taxonomy.name} value={taxonomy}>
{taxonomy.name} от {moment(taxonomy.date).format('YYYY-MM-DD')}
</MenuItem>
))}
</Select>
</FormControl>
</Grid>
);
};
The values that I pass as props are correctly displaying as filled out in the console at all stages the component is being rendered. And also in the case when this component is used for selection through using handleTaxonomyChange function everything is working correctly with user being able to select a particular option out of the array provided to the MenuItem. However, the problem occurs in case when the parent component of this component is being open for View Only or with already pre-defined values. In this case I get the following:
It seems like there's something is being passed to the Select component (even I checked through React Component in DevTools and value was showed correctly) but for some reason it is not being displayed.
The parent component contains the following code related to this part:
const INITIAL_SELECTED_TAXONOMY = null;
const [selectedTaxonomy, setSelectedTaxonomy] = useState(INITIAL_SELECTED_TAXONOMY);
const handleTaxonomyChange = (e) => setSelectedTaxonomy(e.target.value);
useEffect(() => {
getTaxonomies();
}, []);
useEffect(() => {
if (viewTypeOnlyView) {
handleStageChange(1);
handleDialogTitleChange('Конструктор КС. Режим просмотра');
}
if (viewTypeEdit) {
handleDialogTitleChange('Конструктор КС. Режим редактирования');
}
if (viewTypeCopy) {
handleDialogTitleChange('Конструктор КС. Дублирование КС');
}
if (defaultData) {
if (defaultData.name) setName(defaultData.name);
if (defaultData.taxonomy) setSelectedTaxonomy(defaultData.taxonomy);
// if (defaultData.entryPoints) setSelectedEntryPoints(defaultData.entryPoints);
if (defaultData.entryPoints) {
getEntryPointDescsFn('4.1', defaultData.entryPoints);
}
if (defaultData.message) setMessage(defaultData.message);
}
}, [viewType]);
ViewType is a prop that is being passed to this component and calling those methods in order to fill up the state with predefined values.
And the TaxonomySelector component inside the return statement:
<TaxonomySelector
taxonomies={taxonomies}
isDisabled={currentStage === 1}
selectedTaxonomy={selectedTaxonomy}
handleTaxonomyChange={handleTaxonomyChange} />
At first I thought that the issue could be related to how the component is being rendered and maybe it renders before that data pre-fill useEffect hook is being triggered. However, it seems that other elements, like the ones with string values name and message are being correctly filled out with no issues. Seems like that the issue is specifically related to Select elements. Could you let me know what could it possibly be?
Looks like disabled prop in FormControl is true.
For debug set disabled prop false

Connect Material-ui ToggleButtonGroup to redux-form

I'm trying to connect material-ui ToggleButtonGroup with redux form and getting issues with this.
Here is my code:
<Field
name='operator'
component={FormToggleButtonGroup}
>
<ToggleButton value='equals'>Equal</ToggleButton>
<ToggleButton value='not_equals'>Not equal</ToggleButton>
</Field>
.. and my component, passed to Field:
const FormToggleButtonGroup = (props) => {
const {
input,
meta,
children
} = props;
return (
<ToggleButtonGroup
{...input}
touched={meta.touched.toString()}
>
{children}
</ToggleButtonGroup>
);
};
export default FormToggleButtonGroup;
the problem is, when I select value (toggle option), selected value is not passed to redux store, it passed only after loosing focus and then throws error 'newValue.splice is not a function'
Please help to deal with this issue
Sandbox with sample code
Playing with the component I finally found the solution.
I need manually assign new value got from ToggleButtonGroup component and put this value to redux store. Here is how working code looks:
const FormToggleButtonGroup = (props) => {
const {
input,
meta,
children,
...custom
} = props;
const { value, onChange } = input;
return (
<ToggleButtonGroup
{...custom}
value={value}
onChange={(_, newValue) => {
onChange(newValue);
}}
touched={meta.touched.toString()}
>
{children}
</ToggleButtonGroup>
);
};
Main change is getting redux's function onChange and call it with new value, selected when value toggled. There is onChange related to ToggleButtonGroup component and another onChange related to Redux. You need to call latter when ToggleButtonGroup's onChange occurs.

Is my entire React component re-rendering unnecessarily when the state changes?

I am trying to create an accordion component using React, but the animation is not working.
The basic idea is, I believe, pretty standard, I am giving each item body a max-height of 0 which is affected by adding a show class to an element. I am able to select and show the item I want, but the animation to slide in/out is not working.
With the Chrome dev tools open, when I click on one of the items I can see that the whole "accordion" element is flashing, which leads me to believe that the whole element is being re-rendered. But I am unsure why this would be the case.
Here is the relevant Accordion component:
import React, { useState } from "react";
const Accordion = ({ items }) => {
const [selectedItem, setSelectedItem] = useState(0);
const AccordionItem = ({ item, index }) => {
const isOpen = index === selectedItem;
return (
<div className="accordion-item">
<div
onClick={() => {
setSelectedItem(index);
}}
className="accordion-header"
>
<div>{item.heading}</div>
</div>
<div className={`accordion-body ${isOpen ? "show" : ""}`}>
<div className="accordion-content">{item.body}</div>
</div>
</div>
);
};
return (
<div className="accordion">
{items.map((item, i) => {
return <AccordionItem key={i} item={item} index={i} />;
})}
</div>
);
};
export default Accordion;
And here is a codepen illustrating the problem:
https://codesandbox.io/s/heuristic-heyrovsky-xgcbe
of course, its going to re-render. When ever you call setSelectedIem, state changes and hence react re-renders on state change to exhibit that change.
Now if you place this
const [selectedItem, setSelectedItem] = useState(0);
inside Accordion Item, it would just re-render accordion item, but would mess up your functionality.

Closing a dropdown in React-Native on the next press

I have a ScrollView which contains multiple View components as children. Every child can have a dropdown.
Opening the dropdown on a button press works as it should.
Closing the dropdown on the same button or when something inside the dropdown is pressed works too.
Now I gave this a user and they just opened dropdowns over dropdowns without choosing anything or bothering to close the opened dropdowns.
Is there a way to set an event handler for the next press on the screen after a dropdown was opened so the dropdown closes if the user wants to do something different?
Edit
This is kinda my implementation:
const App = () =>
<View>
...
<List items={["one", "two", "three"]}/>
...
</View>
const List = props =>
<ScrollView>
{props.items.map(i => <ListItem name={i} key={i}/>)}
</ScrollView>
class ListItem extends React.Component {
state = { showDropdown: false};
handleDropdown = () =>
this.setState(state =>
({showDropdown: !state.showDropdown})
);
render() {
return <View>
<TouchableOpacity onPress={this.handleDropdown}>
<Text>{this.props.name}</Text>
</TouchableOpacity>
{this.state.showDropdown &&
<Dropdown>
<DropdownItem onPress={this.handleDropdown}/>
</Dropdown>
}
</View>
}
}
The dropdown closes when I click on an ListItem again or when I click on a DropdownItem.
But I also want it to close, when I click somewhere else on the screen, outside of the List component and its children.
Found a solution.
I added a PanResponder to my my apps root View and used this config:
const handlers = []
const addHandler = handler => handlers.push(handler);
const handleNextPress = (event, state) => handlers.forEach(h => h(event, state));
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: (event, state) =>
handleNextPress(event, state)
});
// somewhere else in the app
addHandler(this.closeMyDropdown);
The onStartShouldSetPanResponderCapture method is called every time a touch happens to check if the touch event should be captured. If it returns a falsy value the event isn't captured and hits the touchable components.
This method allows to sneak in handlers that can do things before the event hits the touchable components of the app or use a timeout to let things happen after the touchable components have reacted to the event.
Ideally, you'll want to make the dropdown a controlled component, with a prop that controls whether the dropdown is shown or not, and a callback the component calls when it's tapped.
You can then keep the active dropdown id in the parent component state, and when that is changed, all dropdowns should rerender
Something like:
class List extends Component {
state = {
openDrowdownId: null
}
openDropDown = id => {
this.setState({ openDropDownId: id });
}
closeDropDown = () => {
this.setState({ openDropDownId: null });
}
render() {
return (
<ScrollView>
{this.props.items.map(item => (
<View key={item.id}>
<Dropdown
isOpen={this.state.openDropDownId === item.id}
open={() => this.openDropDown(item.id)}
/>
</View>
))}
</ScrollView>
)
}
}
What you can do is to set a ref on the dropdown like
ref="dropdown"
and on the button press
onPress={() => this.refs.dropdown.blur(); }
This is like define an id and on button click to tell that this is is going to blur

Categories