1

I have a MUI Datagrid with 2 columns, ID and City Name, there are actually only 3 cities in the table. I have a citizen object like this:

const userMockup = {
  id: 1,
  name: "Citizen 1",
  cities: [1, 2],
  isAlive: true
};

The cities array in userMockup represents the cities in which the user lives (with their respective IDs).

I want the rows of the respective cities in which the user lives to be selected when the page loads, I read some DataGrid documentation but with my current code every row gets selected, I need only the rows with id 1 and 2 to be selected, since those are the user cities.

I suspect that something is wrong in the filter part of the selectionModel state.

Here is my code so far, hope you can help me!

Edit initialize-checkbox-selection-based-on-array-values-datagrid-mui

1 Answer 1

1

I think your row filtering logic needs a bit of adjustment. It should be:

rows.filter((r) => userMockup.cities.includes(r.id))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! This definitely solves my question. I have one more question that I would like to know if you have the answer, if the cities array in userMockup object is like this: cities: [{id: 1}, {id: 2}] instead of an array of number, how can you do the filtering? Since this way, the filtering throws this exception: Argument of type 'number' is not assignable to parameter of type '{ id: number; }'
You would have to use either the userMockup.cities.find or userMockup.cities.findIndex methods instead. Google "Array.find()" and read more on MDN for examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.