What is React shadow DOM?
Answer
React shadow DOM is a feature that allows developers to encapsulate the styles and markup of a component, preventing them from leaking out and affecting other parts of the application. It is a way of creating a boundary around a component, so that it can be used in different parts of the application without worrying about its styles or markup interfering with other components. Shadow DOM is a part of the Web Components specification, and React provides a way to use it through the use of the createShadowRoot()
method.
When a component is created with a shadow DOM, it creates a new DOM tree that is separate from the main document tree. This means that the styles and markup of the component are contained within the shadow DOM, and are not affected by the styles and markup of other components or the main document. This allows for greater modularity and reusability of components, as they can be used in different parts of the application without worrying about their styles or markup affecting other components.
Here is an example of how to create a component with a shadow DOM in React:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.shadowRoot = this.attachShadow({ mode: 'open' });
}
render() {
return (
<div>
<style>
h1 {
color: red;
}
</style>
<h1>Hello, world!</h1>
</div>
);
}
}
In this example, the attachShadow()
method is used to create a new shadow root for the component. The mode
option is set to open
, which allows the shadow DOM to be accessed from outside the component. The styles and markup for the component are then added to the shadow DOM using the <style>
and <h1>
tags. This creates a component that can be used in different parts of the application without worrying about its styles or markup affecting other components.
Related React job interview questions
How is React shadow DOM different than virtual DOM?
React JuniorWhat is React virtual DOM?
React JuniorWhat are bundlers in React?
React JuniorWhat is JSX in React?
React JuniorWhat is prop drilling in React?
React Junior