Skip to content

react-hot-loader integration with react-on-rails and webpacker HMR with example

License

Notifications You must be signed in to change notification settings

tahsin352/react-hot-loader-react-on-rails-webpack-hmr

Repository files navigation

react-hot-loader-react-on-rails-webpack-hmr

react-hot-loader integration with react-on-rails and webpacker HMR with example

we will use webpacker hmr

if (module.hot) {
  module.hot.accept('../bundles/HelloWorld/components/Search.jsx', () => {
    render(require('../bundles/HelloWorld/components/Search.jsx').default);
  });
}

It reflects the changes that we made on the codebase in the browser without any page refresh. But it will lost the state of the application. So, we need to use react-hot-loader to keep the state in the app intact.

//client/bundles/HelloWorld/components/Hello.jsx
import React from 'react';
import { hot } from 'react-hot-loader/root';
class Hello extends React.Component {
    constructor(props) {
      super(props);
      this.state = { text: '' };
      this.handleChange = this.handleChange.bind(this);
    }
  
speak = function() {
  alert('I can speak gjhgdjs');
};

handleChange(event) {
  this.setState({text: event.target.value});
}

render() {
  return (<div>
    <h1>23Hello World</h1>
    <input type="text" value={this.state.text} onChange={this.handleChange}/>
    <br/>
    <br/>
    <button id="speak" onClick={ this.speak }>Saysss something</button>
  </div>)
}

} export default hot(Hello);

Now rails + react + react_on_rails + webpack + react_hot_loader works perfectly.

HOC with railsContext

railsContext is available for each react component as 2nd parameter. But when we implement HOC, then it return empty. Coz, only props can be passed from parent component to child component. So, if you want to pass railsContext to child component, then you need to pass it as props like below:
//client/bundles/HelloWorld/components/WithSearch.jsx
import React from 'react';
import SearchContext from './SearchContext';
const WithSearch = (WrappedComponent) => (props, railsContext) => {
    return (
  <div>
    <WrappedComponent {...{...props, railsContext}} />
  </div>
     
    )
  }
export default WithSearch(SearchContext);

//client/bundles/HelloWorld/components/SearchContext.jsx
import React from 'react';
import { hot } from 'react-hot-loader/root';
const SearchContext = (props) => (
Your locale is {props.railsContext.i18nLocale}.
Hello, {props.name}!
);
export default hot(SearchContext);

Contact with Us

Our expertise here. You can buy our popular products from GarazLab

About

react-hot-loader integration with react-on-rails and webpacker HMR with example

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published