Search code examples
reactjscomponentsmountrebuild

Rebuild ReactJs Component


I have a reactjs component(compA) in my app that call another reactjs component(compB) to mount compA.

Inside compB, I have a button that, in function "componentDidUpdate" I need to destroy and rebuild compA.

Anybody has idea how to do this?


The approximate code is this, but, in my code compA and B they are in different files.

use strict';

var CompA = React.createClass({
    getDefaultProps: function() {
        return {
            name: 'location',
        }
    },
    render: function () {
        return <CompB name={this.props.name}/>;
    }
});

var CompB = React.createClass({
    getDefaultProps: function() {
        return {
            name: 'select'
        }
    },
    componentDidUpdate: function() {
        $('.button').click(function() {
            /*
             * RELOAD HERE COMPONENT
             */
        });
    },
    render: function () {
        return <div><select name={this.props.name}><option value="x">X</option><option value="y">Y</option></select><button id="button">Reload</button></div>
    }
});

ReactDOM.render(<CompA />, document.getElementsByID("compA"));
<html>
<body>
  <div id="compA"></div>

  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script src="https://fb.me/react-0.14.7.js"></script>
  <script src="https://fb.me/react-dom-0.14.7.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>

  <script src="comp.jsx" type="text/jsx"></script>
</body>


Solution

  • You can't rebuild an entire CompA from CompB, but calling setState from CompB will rebuild CompB and, in your case, the entire CompA (because you do not have anything else inside it).

    If you want to rebuild a component from an Ajax source, you can have a look at: React Js: How to reload the initila data loaded via ajax?