user1072337
user1072337

Reputation: 12935

Updating text after button click with react.js

I am exploring React.js, and I am trying to do something fairly simple. I would like to update the text of a certain portion of my web app when a user successfully submits their email.

What I have so far:

var SignupForm = React.createClass({
  getInitialState: function() {
    return {email: ''};
  },

  render: function() {
    var email = this.state.value;
    return (
      <div>
        <input type="email" className="input_field" ref="email" value={email} />

        <a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
      </div>
    )
  },

  saveAndContinue: function(e) {
    e.preventDefault()

    // Get values via this.refs

    email = this.refs.email.getDOMNode().value

    request = $.ajax({ 
          url: "/store", 
          type: "post", success:function(data){
            this.setState({email: data})
          }, 
          data: {'email': email} ,beforeSend: function(data){console.log(data);} 
    });

  }
});

React.render(<SignupForm/>, document.getElementById('content'));

The text that I want to update is in an html element like so:

<h1 class="home-two-question">This is the text!</h1>

I want to update it to:

<h1 class="home-two-question">You entered the text!</h1>

after the email has been successfully submitted. Any idea of how to do this?

Upvotes: 3

Views: 6276

Answers (1)

Dhiraj
Dhiraj

Reputation: 33618

I would suggest placing all elements in React components.

You can place it in another component and establish a communication between components or place in one component.

The below is a case where h1 is in the same component.

Add a ref attribute like this

<h1 class="..." ref="myh1"></h1>

in componentDidMount the h1 reference can be stored like this (syntax differs based on react version)

componentDidMount: function () {
  this.myh1 = React.findDOMNode(this.refs.myh1);
}

now that you have a reference you can update it from anywhere like this

$(this.myh1).html(...);

Upvotes: 1

Related Questions