3

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?

3
  • is the h1 part of another react component ? or just outside react components ? Commented Jul 1, 2015 at 1:05
  • it's outside right now, but if I put it in the react components would that help? Commented Jul 1, 2015 at 1:51
  • Yeah, you want your <h1> as another react component. React manages the elements state(ish) (and thus the text inside of it) Commented Jul 1, 2015 at 2:31

1 Answer 1

1

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(...);
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't there a better way to update this with state? Wouldn't the jquery .html be slower?
AFAIK, this is a better way and no it won't be slower. If you don't like it you can still write in vanilla JS to it this.myh1.innerHTML=..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.