9

I'm new to react, I'm curious how to do this properly. suppose I have this form, by clicking button, I want to get textbox value,

var form = React.createClass({
   submit : function(e){
      //how to get textbox value?
   },
   render : function(){
   return (
      <form>
         <input type="text" id="textbox" value="hey, get me"/>
         <button onClick={this.submit}>Get it</button>
      </form>
      );
   }
});

Any answer will be appreciated! thank you!

3
  • 1
    You don't want to interact with the DOM like this with React
    – Mark C.
    Commented Sep 26, 2016 at 1:25
  • how it should be? @MarkC.
    – Angger
    Commented Sep 26, 2016 at 1:27
  • 1
    you should use managed components in component state - read the react docs
    – erik-sn
    Commented Sep 26, 2016 at 1:29

3 Answers 3

8

React enforces parent-to-child unidirectional data flow. So, there's no simple way to access data from siblings.

But, if a child changes the state across the component, you probably want a state for keeping a track of that.

Sample code:

var FormBox = React.createClass({
  getInitialState: function () {
    return {
      textBox: 'hey, get me!'
    }
  },
  pressButton: function () {
    alert(this.state.textBox)
  },
  textChange: function (e) {
    this.setState({
      textBox: e.target.value
    })
  },
  render: function () {
    return (
      <form action='.'>
        <input type='text' placeholder={this.state.textBox} onChange={this.textChange}/>
        <button onClick={this.pressButton}> Get it </button>
      </form>
    )
  }
})

ReactDOM.render(<FormBox />, document.getElementById('root'))

JSBin demo: https://jsbin.com/koxujuwope/edit?js,output

Also, just a suggestion... You should move to ES2015

2
  • how if i want to upload image file? please help :D
    – Angger
    Commented Sep 26, 2016 at 3:49
  • @Angger ES2015 is the new version of Javascript. Has a lot of new features that help with React development. Check it out at babeljs.io . As for the file upload, check out this component: github.com/okonet/react-dropzone
    – trve.fahad
    Commented Sep 26, 2016 at 11:51
5

One way to accomplish this is using refs.

After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from render(). link to refs docs

Refs are basically the html elements / react instances you want to access. In this case, we want to get Input html element. We get input element by this.inputValue. Then read its value by usual js rule.

 var form = React.createClass({
       submit : function(e){
          e.preventDefault();
          console.log(this.inputValue.value);
       },
       render : function(){
       return (
          <form onSubmit={this.submit}>
             <input type="text" id="textbox" defaultValue="hey, get me"
               ref={ function(node){ this.inputValue = node }.bind(this) }
             />
             <button onClick={this.submit}>Get it</button>
          </form>
          );
       }
    });

here is a jsfiddle for your example, you can check the console for the input value.

Another way to accomplish the same thing is to make your input a controlled element. That means you assign input's value attribute to this.state.inputValue and you pass a onChange event handler as onChange={yourInputHandlerFunction}.

See the answer which explains this way of accomplishing the same thing.

4
  • 1
    Refs can lead to unwanted DOM manipulations and should be used carefully. Also, string refs are gonna be deprecated soon (according to the docs)
    – trve.fahad
    Commented Sep 26, 2016 at 1:52
  • Thanks for reminding me of deprecation. Although in real life I have been using function callback, for simplicity I used string in the example.
    – FurkanO
    Commented Sep 26, 2016 at 2:00
  • The fiddle also works without <form></form> wrapper (I replaced them with <div> wrapper. I was a little confused why there were two this.submit. The this.submit inside the form can be omitted and it will still work!
    – Iggy
    Commented Mar 21, 2017 at 18:29
  • @Iggy it works for when you type and enter, if there is no form tags wrapping, on enter nothing is gonna happen, however thanks to form tags and onSubmit handler it will work on enter. Actually we can put type="submit" to button and omit onClick handler of button. This would be better.
    – FurkanO
    Commented Mar 21, 2017 at 18:50
0

The following code helps me to setup communication between two siblings. The setup is done in their parent during render() and componentDidMount() calls. It is based on https://reactjs.org/docs/refs-and-the-dom.html

class App extends React.Component<IAppProps, IAppState> {
    private _navigationPanel: NavigationPanel;
    private _mapPanel: MapPanel;

    constructor() {
        super();
        this.state = {};
    }

    // `componentDidMount()` is called by ReactJS after `render()`
    componentDidMount() {
        // Pass _mapPanel to _navigationPanel
        // It will allow _navigationPanel to call _mapPanel directly
        this._navigationPanel.setMapPanel(this._mapPanel);
    }

    render() {
        return (
            <div id="appDiv" style={divStyle}>
                // `ref=` helps to get reference to a child during rendering
                <NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
                <MapPanel ref={(child) => { this._mapPanel = child; }} />
            </div>
        );
    }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.