Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically change the content of a React Bootstrap modal?

I'm trying to change the content of the modal after it has mounted, but I'm not able to find the correct nodes to change. I've attached refs to the nodes I'm interested in and try to alter them in componentDidMount(). But the nodes are not found -- comes up as null.

var Modal = ReactBootstrap.Modal;


const MyModal = React.createClass({

  getInitialState() {
    return { showModal: false };
  },

  close() {
    this.setState({ showModal: false });
  },

  open() {
    this.setState({ showModal: true });
  },


  componentDidMount() {
    var theNode = ReactDOM.findDOMNode(this.refs.bigPic);
    var theOtherNode = ReactDOM.findDOMNode(this.refs.bigPicInfo);
    theNode.src = 'http://big-pic.png';
    theOtherNode.innerHTML = "<strong> Something here</strong>";
  },

  render() {
    return (
        <div>
        <Modal show={this.state.showModal} onHide={this.close}>
          <Modal.Header closeButton>
            <Modal.Title></Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div><img ref="bigPic" src="" /></div>
          </Modal.Body>
          <Modal.Footer>
            <p ref="bigPicInfo"></p>
          </Modal.Footer>
        </Modal>
        </div>
    );
  }
});

ReactDOM.render(<MyModal/>, document.getElementById("my-modal"));
like image 911
Wally Avatar asked May 12 '16 02:05

Wally


1 Answers

Dynamic content in React is driven by component state, the same way you're using this.state.showModal to dynamically make the modal appear or not. Anything that can possibly change should have a default setting in getInitialState, then call this.setState() with your new values.. this will trigger your component to re-render.

const MyModal = React.createClass({

  getInitialState() {
    return { 
      showModal: false,
      bigPicSrc: '',
      infoContent: ''
    }
  },

  ...

  componentDidMount() {
    this.setState({ 
      bigPicSrc: 'http://big-pic.png'
      infoContent: <strong>Something here</strong> // not a string, but a component
    })
  },

  render() {
    return (
      <Modal show={this.state.showModal} onHide={this.close}>
        <Modal.Header closeButton>
          <Modal.Title></Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div><img ref="bigPic" src={this.state.bigPicSrc} /></div>
        </Modal.Body>
        <Modal.Footer>
          <p ref="bigPicInfo">{this.state.infoContent}</p>
        </Modal.Footer>
      </Modal>
    )
  }
})
like image 89
azium Avatar answered Sep 19 '22 21:09

azium