top of page
Logo der Online Agentur mdwp

Escape Hatches

Escape Hatches in React Js refers to the instances where you need to interface with a third-party DOM library or you need to perform some operation directly on the DOM that isn't supported by React. React is predominantly used for working with the Virtual DOM, but at times you might need to directly interact with the actual DOM that gets rendered in the web browser. These instances where you opt out of the normal data flow and operate on the underlying DOM or use third-party DOM libraries are referred to as 'Escape Hatches'.

For example, using 'refs' in React is a form of an escape hatch. Refs provide a way to access DOM nodes or React elements created in the render method.

Here's a code snippet:

```javascript
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}

render() {
return <div ref={this.myRef}>Hello World!</div>;
}

componentDidMount() {
// you can perform operations on the DOM node through the 'current' property
console.log(this.myRef.current);
}
}
```

In this example, we've created a 'ref' using `React.createRef()` and attached it to a div element in the render function. After the component has been mounted, we can access the actual DOM node through `this.myRef.current`.

This is a kind of escape hatch since we're breaking out of React's normal declarative props down / events up paradigm and doing imperative operations directly on the DOM. It's generally recommended to avoid using escape hatches, but sometimes it's necessary to interface with other libraries or perform operations that are not yet supported by React.

bottom of page