How to import and export with React cdn?

Does anyone know if you can export/import a component using the React cdn?

I'm trying to export a class component from another file so that I can route/link to it.

class RouteC extends React.Component {
  btnClickA() {
    browserHistory.push('/a');
  }

  btnClickB() {
    browserHistory.push('/b');
  }

  render() {
    return(
      <div>
        <h2>Route C</h2>
        <div>
          <button className="btn btn-default" onClick={ this.btnClickA }>Goto A</button>
          <button className="btn btn-default" onClick={ this.btnClickB }>Goto B</button>
        </div>
      </div>
    );
  }
}

ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={RouteA} />
    <Route path="/a" component={RouteA} />
    <Route path="/b" component={RouteB} />
    <Route path="/c" component={RouteC} />
    <Route path="*" component={RouteA} />
  </Router>,
  document.getElementById('app')
);

I'm trying to do something similar to this (https://codepen.io/lsmoura/pen/pNPOzp), but imagine if components A and B are in separate files.

I've already tried using export default class but that produced an error. From my search it has something to do with CommonJS and ES6. I don't want to use webpack or browserify as I'm not sure how to integrate that with my backend which is Flask. Any suggestions or help would be deeply appreciated, thanks.

1 answer

  • answered 2019-08-23 23:40 Isaac

    Copy the entire RouteA class component into another file /src/Components/RouteA, add import React from 'react'; and add export default RouteA. Final version should be as below

    import React from 'react';
    
    class RouteA extends React.Component {
      btnClickB() {
        browserHistory.push('/b');
      }
      btnClickC() {
        browserHistory.push('/c');
      }
    
      render() {
        return(
          <div>
            <h2>Route A</h2>
            <div>
              <button className="btn btn-default" onClick={ this.btnClickB }>Goto B</button>
              <button className="btn btn-default" onClick={ this.btnClickC }>Goto C</button>
            </div>
          </div>
        );
      }
    }
    
    export default RouteA;
    

    Then import RouteA when you need it.

    import RouteA from './src/Components/RouteA';