Skip to content

Instantly share code, notes, and snippets.

@Rajdeepc
Created May 11, 2020 09:22
Show Gist options
  • Select an option

  • Save Rajdeepc/3bb3101a515fc9e3dab7817fe45e2206 to your computer and use it in GitHub Desktop.

Select an option

Save Rajdeepc/3bb3101a515fc9e3dab7817fe45e2206 to your computer and use it in GitHub Desktop.
dynamic imports and code splitting in React
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
class App extends Component {
state = {
modal: null
}
showLocation = () => {
// dynamically importing the Modal component so that it doesnt render in the dom before it is required
import('./components/Modal')
.then((mod) => this.setState(() => ({
modal: mod.default
})
))
}
render() {
const { modal: Modal } = this.state;
return (
<>
<div>Testing Code Splitting or Lazy loading of components</div>
<br></br>
{Modal !== null ?
<Modal />
:
<button onClick={this.showLocation}>
Show Modal
</button>
}
</>
)
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment