I'm building a React component, which currently displays a list of technologies. The user can toggle which of these technologies are 'active' (i.e. selected) by clicking on them. They start as false, change to true, back to false and so on.
When the user does this, they get added to the overall technologies array and displayed on the frontend.
This is done through a 'toggleTechnology' function, which gets two properties passed in to it: item (the technology text) and index (where this item is in the array).
const toggleTechnology = (item, index) => {
console.log(item)
console.log(index)
if (technologies.includes(item)) {
let filteredArray = technologies.filter((currentItem, currentIndex) => currentIndex !== index)
setTechnologies(filteredArray)
} else {
setTechnologies(tech => [...tech, item])
}
}
The list of technologies is kept in a separate array, to be displayed dynamically on the frontend, like so:
const frontEndSklls = ['HTML', 'CSS', 'Javascript', 'React', 'Unit tests', 'Vue.js']
{ frontEndSklls.map((item, index) => {
return <span className={technologies.includes(item) ? "toggle-option active" : "toggle-option"} onClick={() => toggleTechnology(item, index)} key={index}>{item}</span>
}) }
My issue comes in when a user adds multiple skills and then removes some of them.
So for example, if they clicked on the following in this order, each item in the technologies array would have an index like this:
0: HTML
1: Unit tests
2: React
3: CSS
However, if they then clicked on 'React' to remove it, the array would go like this:
0: HTML
1: Unit tests
2: CSS
If they then click on CSS to remove it, I think because the new index of CSS is 2, it isn't removing the property. So what you need to do is click on another element first, say React again, and then CSS can be removed as the new array has CSS at index point 2.
So my question: is there a way for me to adjust my code so that the index remains the same for each of the options, even when you click on and off the elements?
The solution to me seems to be to turn each element in the array into an object, and assign a permanent index number and value to each element in the array - but this doesn't feel as clean as it could be.
Any suggestions would be appreciated.
You have two different arrays in the component:
frontEndSkills - static - used to render all technologies in the UI with activated/deactivated status.
technologies - dynamic - the filtered array used to mark the active technologies in the UI as such.
The problem is that you're supplying the index of an item from the frontEndSkills array to be used in the technologies array, which is not always the same as the former.
#Subham Jain's answer also would work perfectly, but here is my shot at it, without the need for the index at all:
const toggleTechnology = (item) => {
if (technologies.includes(item)) {
let filteredArray = [...technologies].filter(currentItem => currentItem !== item)
setTechnologies(filteredArray)
} else {
setTechnologies(tech => [...tech, item])
}
}
Note: The suggestion to not use the index as a key from the other answers/comments here is sensible and highly recommended. Please consider that seriously. If you do have to use it for any reason at all, make sure that you understand why it is anti-pattern to do so.
I would suggest that change 2 things.
Instead of using "index" for the "key" use "item".
Do not toggle the state based on the index. To achieve this you can modify the "toggletechnology" as below:-
const toggleTechnology = (item) => {
if (technologies.includes(item)) {
let indexOfItem = technologies.indexOf(item);
let filteredArray = [...technologies].splice(indexOfItem,1);
setTechnologies(filteredArray)
} else {
setTechnologies(tech => [...tech, item])
}
}
Regarding the Master Detail feature of MUI; when exporting to CSV from a Data Grid while implementing Master Detail the CSV export functionality stops working (understandably). Technically it works but only exports the first row (in my case). I looked around for a disable functionality of the master detail like there is for disableRowGrouping prop for groups but was not able to find one. Does this functionality exist and if not, do you have any suggestions on how I can turn on and off the Master Detail prop?
I did try conditionally adding the master detail feature to the DataGridPro component using state and a ternary statement like {!!someState ? getDetailPanelContent={({ row }) => <div>Row ID: {row.id}</div>}: false} however was not able to do so. I'm not sure if you can have conditional component props. Is this when a spread operator is used? If so, maybe someone can give an example of how to implement these two together?
I believe this is what you might call a rookie mistake. I was applying a ternary operation to the entire property and not just the value of the property.
Incorrect: {!!someState ? getDetailPanelContent={({ row }) => <div>Row ID: {row.id}</div>}: false}
Correct: {getDetailPanelContent= {!!someState ? {({ row }) => <div>Row ID: {row.id}</div>}: false} : null}.
Here is a code snippet:
// Custom State to manage disabling of panelContent
const [disablePanelContent, setDisablePanelContent] = useState(true);
// queryResponse is data being put into the DataGrid; '[0]' being the first row returned
// columnToTrigger is the column from the queryResponse that I want to trigger either showing or disabling the panelContent
if (!!queryResponse[0].columnToTrigger {
setDisablePanelContent(false);
} else {
setDisablePanelContent(true);
}
< DataGridPro
// ...
getDetailPanelContent = {!!disablePanelContent ? null : getDetailPanelContent} // Answer
// ...
/>
The solution below didn't work for me to conditionally render the expand icons for the master detail, so I wanted to share my working solution:
// MUI: Always memoize the function provided to getDetailPanelContent and getDetailPanelHeight.
const getDetailPanelContent = useCallback((params: GridRowParams<any>) => <CustomDetailPanel params={params} rowExpansion={rowExpansion}/>, []);
// Inside of the datagrid - conditionally render based on rowExpansion
{...(_.isEmpty(rowExpansion) ? {} : { getDetailPanelContent:getDetailPanelContent })}
This is a difficult one to explain so I will do my best!
My Goal
I have been learning React and decided to try build a Todo List App from scratch. I wanted to implement a "push notification" system, which when you say mark a todo as complete it will pop up in the bottom left corner saying for example "walk the dog has been updated". Then after a few seconds or so it will be removed from the UI.
Fairly simple Goal, and for the most part I have got it working... BUT... if you quickly mark a few todos as complete they will get removed from the UI and then get re-rendered back in!
I have tried as many different ways of removing items from state as I can think of and even changing where the component is pulled in etc.
This is probably a noobie question, but I am still learning!
Here is a link to a code sandbox, best way I could think of to show where I am at:
Alert Component State/Parent
https://codesandbox.io/s/runtime-night-h4czf?file=/src/components/layout/PageContainer.js
Alert Component
https://codesandbox.io/s/runtime-night-h4czf?file=/src/components/parts/Alert.js
Any help much appreciated!
When you call a set function to update state, it will update from the last rendered value. If you want it to update from the last set value, you need to pass the update function instead of just the new values.
For instance, you can change your setTodos in your markComplete function to something like this.
setTodos(todos => todos.map((todo) => {
if (id === todo.id) {
todo = {
...todo,
complete: !todo.complete,
};
}
return todo;
}));
https://codesandbox.io/s/jovial-yalow-yd0jz
If asynchronous events are happening, the value in the scope of the executed event handler might be out of date.
When updating lists of values, use the updating method which receives the previous state, for example
setAlerts(previousAlerts => {
const newAlerts = (build new alerts from prev alerts);
return newAlerts;
});
instead of directly using the alerts you got from useState.
In the PageContainer.js, modify this function
const removeAlert = (id) => {
setAlerts(alerts.filter((alert) => alert.id !== id));
};
to this
const removeAlert = (id) => {
setAlerts(prev => prev.filter((alert) => alert.id !== id));
};
This will also fix the issue when unchecking completed todos at high speed
everyone. New to asking questions here, although I use it to find answers pretty frequently. My issue is this:
I have a "to do list" application. I'm able to add, delete, and mark to do items complete. However, what I'm struggling with is the filter for viewing the different items (view all, only active, and only completed).
I have everything built around the buttons and the click event, but what I can't seem to figure out is how to actually display the desired to do items. Clicking the buttons returns an error that todo.filter is not a function, so I'm apparently off in left field somewhere with my current solution.
Here is the code I'm using to try to filter the array and show only the to do items with the boolean completed: true.
filComplete = id => {
this.setState({
todos: this.state.todos.map(todo => {
let comTodo = todo.filter(todo => todo.completed = true);
return comTodo;
})
})
}
From my own understanding, I am mapping all of the todo items where completed is true to a new array for display, but I'm obviously not doing something right.
todo is each individual todo item.
todos is the array of todo items.
id is the key of todo.id.
Thanks in advance.
let comTodo = todo.filter(todo => todo.completed = true);
Using a single = is an assignment, not a comparison. Instead, you can just use
let comTodo = todo.filter(todo => todo.completed);
if completed is a Boolean. You also don't need to combine map with filter if all you want is simple filtering, so the final production would look like
filComplete = id => {
this.setState({
todos: this.state.todos.filter(todo => todo.completed)
})
}
Don't bother with map - that just transforms an array to another of the same length. Just use filter to check the completed property and remove those incomplete todos:
this.setState({
todos: this.state.todos.filter(todo => todo.completed)
});
Although note that doing this means that, once you're only showing the completed todos, you can't recover the full list. You probably want the full list in your props, not state.
One other potential problem with this is that setState is asynchronous, and therefore doesn't always work correctly when you reference this.state inside it - as that won't always have the value you expect. Instead, pass in function which describes how to transform the old state to the new:
this.setState(state => ({
todos: state.todos.filter(todo => todo.completed)
}));
I am in the process of implementing a filterable list with React. The structure of the list is as shown in the image below.
PREMISE
Here's a description of how it is supposed to work:
The state resides in the highest level component, the Search component.
The state is described as follows:
{
visible : boolean,
files : array,
filtered : array,
query : string,
currentlySelectedIndex : integer
}
files is a potentially very large, array containing file paths (10000 entries is a plausible number).
filtered is the filtered array after the user types at least 2 characters. I know it's derivative data and as such an argument could be made about storing it in the state but it is needed for
currentlySelectedIndex which is the index of the currently selected element from the filtered list.
User types more than 2 letters into the Input component, the array is filtered and for each entry in the filtered array a Result component is rendered
Each Result component is displaying the full path that partially matched the query, and the partial match part of the path is highlighted. For example the DOM of a Result component, if the user had typed 'le' would be something like this :
<li>this/is/a/fi<strong>le</strong>/path</li>
If the user presses the up or down keys while the Input component is focused the currentlySelectedIndex changes based on the filtered array. This causes the Result component that matches the index to be marked as selected causing a re-render
PROBLEM
Initially I tested this with a small enough array of files, using the development version of React, and all worked fine.
The problem appeared when I had to deal with a files array as big as 10000 entries. Typing 2 letters in the Input would generate a big list and when I pressed the up and down keys to navigate it it would be very laggy.
At first I did not have a defined component for the Result elements and I was merely making the list on the fly, on each render of the Search component, as such:
results = this.state.filtered.map(function(file, index) {
var start, end, matchIndex, match = this.state.query;
matchIndex = file.indexOf(match);
start = file.slice(0, matchIndex);
end = file.slice(matchIndex + match.length);
return (
<li onClick={this.handleListClick}
data-path={file}
className={(index === this.state.currentlySelected) ? "valid selected" : "valid"}
key={file} >
{start}
<span className="marked">{match}</span>
{end}
</li>
);
}.bind(this));
As you can tell, every time the currentlySelectedIndex changed, it would cause a re-render and the list would be re-created each time. I thought that since I had set a key value on each li element React would avoid re-rendering every other li element that did not have its className change, but apparently it wasn't so.
I ended up defining a class for the Result elements, where it explicitly checks whether each Result element should re-render based on whether it was previously selected and based on the current user input :
var ResultItem = React.createClass({
shouldComponentUpdate : function(nextProps) {
if (nextProps.match !== this.props.match) {
return true;
} else {
return (nextProps.selected !== this.props.selected);
}
},
render : function() {
return (
<li onClick={this.props.handleListClick}
data-path={this.props.file}
className={
(this.props.selected) ? "valid selected" : "valid"
}
key={this.props.file} >
{this.props.children}
</li>
);
}
});
And the list is now created as such:
results = this.state.filtered.map(function(file, index) {
var start, end, matchIndex, match = this.state.query, selected;
matchIndex = file.indexOf(match);
start = file.slice(0, matchIndex);
end = file.slice(matchIndex + match.length);
selected = (index === this.state.currentlySelected) ? true : false
return (
<ResultItem handleClick={this.handleListClick}
data-path={file}
selected={selected}
key={file}
match={match} >
{start}
<span className="marked">{match}</span>
{end}
</ResultItem>
);
}.bind(this));
}
This made performance slightly better, but it's still not good enough. Thing is when I tested on the production version of React things worked buttery smooth, no lag at all.
BOTTOMLINE
Is such a noticeable discrepancy between development and production versions of React normal?
Am I understanding/doing something wrong when I think about how React manages the list?
UPDATE 14-11-2016
I have found this presentation of Michael Jackson, where he tackles an issue very similar to this one: https://youtu.be/7S8v8jfLb1Q?t=26m2s
The solution is very similar to the one proposed by AskarovBeknar's answer, below
UPDATE 14-4-2018
Since this is apparently a popular question and things have progressed since the original question was asked, while I do encourage you to watch the video linked above, in order to get a grasp of a virtual layout, I also encourage you to use the React Virtualized library if you do not want to re-invent the wheel.
As with many of the other answers to this question the main problem lies in the fact that rendering so many elements in the DOM whilst doing filtering and handling key events is going to be slow.
You are not doing anything inherently wrong with regards to React that is causing the issue but like many of the issues that are performance related the UI can also take a big percentage of the blame.
If your UI is not designed with efficiency in mind even tools like React that are designed to be performant will suffer.
Filtering the result set is a great start as mentioned by #Koen
I've played around with the idea a bit and created an example app illustrating how I might start to tackle this kind of problem.
This is by no means production ready code but it does illustrate the concept adequately and can be modified to be more robust, feel free to take a look at the code - I hope at the very least it gives you some ideas...;)
react-large-list-example
My experience with a very similar problem is that react really suffers if there are more than 100-200 or so components in the DOM at once. Even if you are super careful (by setting up all your keys and/or implementing a shouldComponentUpdate method) to only to change one or two components on a re-render, you're still going to be in a world of hurt.
The slow part of react at the moment is when it compares the difference between the virtual DOM and the real DOM. If you have thousands of components but only update a couple, it doesn't matter, react still has a massive difference operation to do between the DOMs.
When I write pages now I try to design them to minimise the number of components, one way to do this when rendering large lists of components is to... well... not render large lists of components.
What I mean is: only render the components you can currently see, render more as you scroll down, you're user isn't likely to scroll down through thousands of components any way.... I hope.
A great library for doing this is:
https://www.npmjs.com/package/react-infinite-scroll
With a great how-to here:
http://www.reactexamples.com/react-infinite-scroll/
I'm afraid it doesn't remove components that are off the top of the page though, so if you scroll for long enough you're performance issues will start to reemerge.
I know it isn't good practice to provide a link as answer, but the examples they provide are going to explain how to use this library much better than I can here. Hopefully I have explained why big lists are bad, but also a work around.
First of all, the difference between the development and production version of React is huge because in production there are many bypassed sanity checks (such as prop types verification).
Then, I think you should reconsider using Redux because it would be extremely helpful here for what you need (or any kind of flux implementation). You should definitively take a look at this presentation : Big List High Performance React & Redux.
But before diving into redux, you need to made some ajustements to your React code by splitting your components into smaller components because shouldComponentUpdate will totally bypass the rendering of children, so it's a huge gain.
When you have more granular components, you can handle the state with redux and react-redux to better organize the data flow.
I was recently facing a similar issue when I needed to render one thousand rows and be able to modify each row by editing its content. This mini app displays a list of concerts with potential duplicates concerts and I need to chose for each potential duplicate if I want to mark the potential duplicate as an original concert (not a duplicate) by checking the checkbox, and, if necessary, edit the name of the concert. If I do nothing for a particular potential duplicate item, it will be considered duplicate and will be deleted.
Here is what it looks like :
There are basically 4 mains components (there is only one row here but it's for the sake of the example) :
Here is the full code (working CodePen : Huge List with React & Redux) using redux, react-redux, immutable, reselect and recompose:
const initialState = Immutable.fromJS({ /* See codepen, this is a HUGE list */ })
const types = {
CONCERTS_DEDUP_NAME_CHANGED: 'diggger/concertsDeduplication/CONCERTS_DEDUP_NAME_CHANGED',
CONCERTS_DEDUP_CONCERT_TOGGLED: 'diggger/concertsDeduplication/CONCERTS_DEDUP_CONCERT_TOGGLED',
};
const changeName = (pk, name) => ({
type: types.CONCERTS_DEDUP_NAME_CHANGED,
pk,
name
});
const toggleConcert = (pk, toggled) => ({
type: types.CONCERTS_DEDUP_CONCERT_TOGGLED,
pk,
toggled
});
const reducer = (state = initialState, action = {}) => {
switch (action.type) {
case types.CONCERTS_DEDUP_NAME_CHANGED:
return state
.updateIn(['names', String(action.pk)], () => action.name)
.set('_state', 'not_saved');
case types.CONCERTS_DEDUP_CONCERT_TOGGLED:
return state
.updateIn(['concerts', String(action.pk)], () => action.toggled)
.set('_state', 'not_saved');
default:
return state;
}
};
/* configureStore */
const store = Redux.createStore(
reducer,
initialState
);
/* SELECTORS */
const getDuplicatesGroups = (state) => state.get('duplicatesGroups');
const getDuplicateGroup = (state, name) => state.getIn(['duplicatesGroups', name]);
const getConcerts = (state) => state.get('concerts');
const getNames = (state) => state.get('names');
const getConcertName = (state, pk) => getNames(state).get(String(pk));
const isConcertOriginal = (state, pk) => getConcerts(state).get(String(pk));
const getGroupNames = reselect.createSelector(
getDuplicatesGroups,
(duplicates) => duplicates.flip().toList()
);
const makeGetConcertName = () => reselect.createSelector(
getConcertName,
(name) => name
);
const makeIsConcertOriginal = () => reselect.createSelector(
isConcertOriginal,
(original) => original
);
const makeGetDuplicateGroup = () => reselect.createSelector(
getDuplicateGroup,
(duplicates) => duplicates
);
/* COMPONENTS */
const DuplicatessTableRow = Recompose.onlyUpdateForKeys(['name'])(({ name }) => {
return (
<tr>
<td>{name}</td>
<DuplicatesRowColumn name={name}/>
</tr>
)
});
const PureToggle = Recompose.onlyUpdateForKeys(['toggled'])(({ toggled, ...otherProps }) => (
<input type="checkbox" defaultChecked={toggled} {...otherProps}/>
));
/* CONTAINERS */
let DuplicatesTable = ({ groups }) => {
return (
<div>
<table className="pure-table pure-table-bordered">
<thead>
<tr>
<th>{'Concert'}</th>
<th>{'Duplicates'}</th>
</tr>
</thead>
<tbody>
{groups.map(name => (
<DuplicatesTableRow key={name} name={name} />
))}
</tbody>
</table>
</div>
)
};
DuplicatesTable.propTypes = {
groups: React.PropTypes.instanceOf(Immutable.List),
};
DuplicatesTable = ReactRedux.connect(
(state) => ({
groups: getGroupNames(state),
})
)(DuplicatesTable);
let DuplicatesRowColumn = ({ duplicates }) => (
<td>
<ul>
{duplicates.map(d => (
<DuplicateItem
key={d}
pk={d}/>
))}
</ul>
</td>
);
DuplicatessRowColumn.propTypes = {
duplicates: React.PropTypes.arrayOf(
React.PropTypes.string
)
};
const makeMapStateToProps1 = (_, { name }) => {
const getDuplicateGroup = makeGetDuplicateGroup();
return (state) => ({
duplicates: getDuplicateGroup(state, name)
});
};
DuplicatesRowColumn = ReactRedux.connect(makeMapStateToProps1)(DuplicatesRowColumn);
let DuplicateItem = ({ pk, name, toggled, onToggle, onNameChange }) => {
return (
<li>
<table>
<tbody>
<tr>
<td>{ toggled ? <input type="text" value={name} onChange={(e) => onNameChange(pk, e.target.value)}/> : name }</td>
<td>
<PureToggle toggled={toggled} onChange={(e) => onToggle(pk, e.target.checked)}/>
</td>
</tr>
</tbody>
</table>
</li>
)
}
const makeMapStateToProps2 = (_, { pk }) => {
const getConcertName = makeGetConcertName();
const isConcertOriginal = makeIsConcertOriginal();
return (state) => ({
name: getConcertName(state, pk),
toggled: isConcertOriginal(state, pk)
});
};
DuplicateItem = ReactRedux.connect(
makeMapStateToProps2,
(dispatch) => ({
onNameChange(pk, name) {
dispatch(changeName(pk, name));
},
onToggle(pk, toggled) {
dispatch(toggleConcert(pk, toggled));
}
})
)(DuplicateItem);
const App = () => (
<div style={{ maxWidth: '1200px', margin: 'auto' }}>
<DuplicatesTable />
</div>
)
ReactDOM.render(
<ReactRedux.Provider store={store}>
<App/>
</ReactRedux.Provider>,
document.getElementById('app')
);
Lessons learned by doing this mini app when working with huge dataset
React components work best when they are kept small
Reselect become very useful to avoid recomputation and keep the same reference object (when using immutable.js) given the same arguments.
Create connected component for component that are the closest of the data they need to avoid having component only passing down props that they do not use
Usage of fabric function to create mapDispatchToProps when you need only the initial prop given in ownProps is necessary to avoid useless re-rendering
React & redux definitively rock together !
Like I mentioned in my comment, I doubt that users need all those 10000 results in the browser at once.
What if you page through the results, and always just show a list of 10 results.
I've created an example using this technique, without using any other library like Redux.
Currently only with keyboard navigation, but could easily be extended to work on scrolling as well.
The example exists of 3 components, the container application, a search component and a list component.
Almost all the logic has been moved to the container component.
The gist lies in keeping track of the start and the selected result, and shifting those on keyboard interaction.
nextResult: function() {
var selected = this.state.selected + 1
var start = this.state.start
if(selected >= start + this.props.limit) {
++start
}
if(selected + start < this.state.results.length) {
this.setState({selected: selected, start: start})
}
},
prevResult: function() {
var selected = this.state.selected - 1
var start = this.state.start
if(selected < start) {
--start
}
if(selected + start >= 0) {
this.setState({selected: selected, start: start})
}
},
While simply passing all the files through a filter:
updateResults: function() {
var results = this.props.files.filter(function(file){
return file.file.indexOf(this.state.query) > -1
}, this)
this.setState({
results: results
});
},
And slicing the results based on start and limit in the render method:
render: function() {
var files = this.state.results.slice(this.state.start, this.state.start + this.props.limit)
return (
<div>
<Search onSearch={this.onSearch} onKeyDown={this.onKeyDown} />
<List files={files} selected={this.state.selected - this.state.start} />
</div>
)
}
Fiddle containing a full working example: https://jsfiddle.net/koenpunt/hm1xnpqk/
Try filter before loading into the React component and only show a reasonable amount of items in the component and load more on demand. Nobody can view that many items at one time.
I don't think you are, but don't use indexes as keys.
To find out the real reason why the development and production versions are different you could try profiling your code.
Load your page, start recording, perform a change, stop recording and then check out the timings. See here for instructions for performance profiling in Chrome.
React in development version checks for proptypes of each component to ease development process, while in production it is omitted.
Filtering list of strings is very expensive operation for every keyup. it might cause performance issues because of single threaded nature of JavaScript.
Solution might be to use debounce method to delay execution of your filter function until the delay is expired.
Another problem might be the huge list itself. You can create virtual layout and reuse created items just replacing data. Basically you create scrollable container component with fixed height, inside of which you will place list container. The height of list container should be set manually (itemHeight * numberOfItems) depending on the length of visible list, to have a scrollbar working. Then create a few item components so that they will fill scrollable containers height and maybe add extra one or two mimic continuous list effect. make them absolute position and on scroll just move their position so that it will mimic continuous list(I think you will find out how to implement it:)
One more thing is writing to DOM is also expensive operation especially if you do it wrong. You can use canvas for displaying lists and create smooth experience on scroll. Checkout react-canvas components. I heard that they have already done some work on Lists.
Check out React Virtualized Select, it's designed to address this issue and performs impressively in my experience. From the description:
HOC that uses react-virtualized and react-select to display large lists of options in a drop-down
https://github.com/bvaughn/react-virtualized-select
For anyone struggling with this problem I have written a component react-big-list that handles lists to up to 1 million of records.
On top of that it comes with some fancy extra features like:
Sorting
Caching
Custom filtering
...
We are using it in production in quite some apps and it works great.
React has recommend react-window library: https://www.npmjs.com/package/react-window
It better than react-vitualized. You can try it
I recently developed multi-select input for React and tested it with 48.000 records. It's working without any problem.
https://www.npmjs.com/package/react-multi-select-advanced
Here's my attempt on this
react-async-lazy-list
OR,
https://github.com/sawrozpdl/react-async-lazy-list
you can give it a shot. it's pretty fast as it uses windowing/virtualization and comes with lazy loading and full customization.