Phanikiran
Phanikiran

Reputation: 181

Traversing / Editing DOM in React JS

I am new to React JS and planning to use it in one of my projects. I have gone through the docs and have a slight idea of React. I have a scenario with the following details :

  1. Server pushes array of items / list to UI in frequent intervals.
  2. The items in the list are not similar to each other or multiple lists but will be displayed in the order they are received.
  3. Items will have to appended to DOM upon AJAX response / push notification from server.
  4. Few cases, will have to edit / delete the items from DOM based on a reference.

I was going through few articles in stack overflow for appending data dynamically and few of them are below :

All the above solutions doesn't provide a direct option for appending. They recommend to create a map / array and add the values to the map and re-render the values.

I am not very comfortable in using maps as I won't be passing the details to server and its only shown to user. I think creating a map will have redundant values which occupies memory if the list grows huge.

I dont want to mix jQuery / any other library along with React. Is there any possibility where a render function / component will append to DOM instead of maintaining in an array as the items in the list are not similar.

Why there isn't any option to traverse / edit DOM directly instead of maintaining a list. Can you guide me if there is an option so that I will be able to understand its advantages.

Upvotes: 0

Views: 1712

Answers (2)

feng_nyc
feng_nyc

Reputation: 157

Hi I was in the exact situation. Switched from jQuery to React recently. The solution is Redux. React wont have any DOM manipulation whatsoever. So forget about the .parent().child().next() things we had before.

Theres this concept in Redux's core. State management. So basically state is a little tool you need to manipulate through the React 'tree'. Kinda like the DOM manipulation in jQuery but not totally the same. The state will flow between siblings, up to parent or down to child

Upvotes: 1

Dmitry Sokurenko
Dmitry Sokurenko

Reputation: 6132

  1. You definitely don't need to use jQuery or any other direct DOM manipulation tool.
  2. There is no need to worry about the fact that your list becomes so huge that it affects the performance / consumes too much memory — the fact that you have a lot of elements in the DOM will hit the resource constraints much sooner. You can easily store way more data in a JSON map/array than you can render.
  3. I believe you don't seed a map, you need an array, but that's not a significant thing.

So just update the data like this when you receive some updates from the server and render will take care about displaying them:

onDataReceived(newData) {
  // or you can mutate the `data` array here, doesn't matter too much
  this.setState({data: data.concat(newData)})
}

render() {
  // render this.state.data
}

Upvotes: 2

Related Questions