Rohan Pota
Rohan Pota

Reputation: 81

What is the difference between below pieces of React code?

First one:-

ReactDOM.render((
  <Provider store={store}>
    <App />
  </Provider>
),document.getElementById('root'));

Second one:-

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>,
  document.querySelector(".container")
);

What I would like to know is that what specifically will be the difference in doing document.querySelector(".container") and document.getElementById('root') ?

Upvotes: 2

Views: 1050

Answers (2)

user9081948
user9081948

Reputation:

If you meant difference between difference in doing document.querySelector(".container") and document.querySelector(".root"),

Then

document.querySelector(".root") --> renders your react code in all elements with class "root"

document.querySelector(".container") --> renders your react code in all elements with class "container"

If you meant difference between difference in doing document.querySelector(".container") and document.getElementById('root') in the question.

Then

document.getElementById('root') --> renders your react code in element with id "root"

document.querySelector(".container") --> renders your react code in all elements with class "container"

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281676

document.getElementById('root') gets the DOM element from your HTML with id root whereas document.querySelector(".container") gets the first element from HTML with class container

According to the MDN docs:

document.querySelector()

Returns the first Element within the document that matches the specified selector, or group of selectors, or null if no matches are found.

document.getElementById()

Returns a reference to the element by its ID; the ID is a string which can be used to uniquely identify the element, found in the HTML id attribute.

So,

in first case your React App will be rendered within the DOM element with id root whereas in second case it will be rendered in the first DOM element with class container

Upvotes: 1

Related Questions