I’m trying my first bit of React.js and am stumped early on… I have the code below, which renders a search form into <div id="search"></div>
. But typing in the search box does nothing.
Presumably something is going missing passing the props and state up and down, and this seems like a common problem. But I’m stumped – I can’t see what’s missing.
var SearchFacet = React.createClass({ handleChange: function() { this.props.onUserInput( this.refs.searchStringInput.value ) }, render: function() { return ( <div> Search for: <input type="text" value={this.props.searchString} ref="searchStringInput" onchange={this.handleChange} /> </div> ); } }); var SearchTool = React.createClass({ render: function() { return ( <form> <SearchFacet searchString={this.props.searchString} onUserInput={this.props.onUserInput} /> <button>Search</button> </form> ); } }); var Searcher = React.createClass({ getInitialState: function() { return { searchString: '' } }, handleUserInput: function(searchString) { this.setState({ searchString: searchString }) }, render: function() { return ( <div> <SearchTool searchString={this.state.searchString} onUserInput={this.handleUserInput} /> </div> ); } }); ReactDOM.render( <Searcher />, document.getElementById('searcher') );
(Eventually I will have other types of SearchFacet*
but I’m just trying to get this one working.)
Advertisement
Answer
You haven’t properly cased your onchange
prop in the input
. It needs to be onChange
in JSX.
<input type="text" value={this.props.searchString} ref="searchStringInput" onchange={this.handleChange} <--[should be onChange] />
The topic of passing a value
prop to an <input>
, and then somehow changing the value passed in response to user interaction using an onChange
handler is pretty well-considered in the docs.
They refer to such inputs as Controlled Components, and refer to inputs that instead let the DOM natively handle the input’s value and subsequent changes from the user as Uncontrolled Components.
Whenever you set the value
prop of an input
to some variable, you have a Controlled Component. This means you must change the value of the variable by some programmatic means or else the input will always hold that value and will never change, even when you type — the native behaviour of the input, to update its value on typing, is overridden by React here.
So, you’re correctly taking that variable from state, and have a handler to update the state all set up fine. The problem was because you have onchange
and not the correct onChange
the handler was never being called and so the value
was never being updated when you type into the input. When you do use onChange
the handler is called, the value
is updated when you type, and you see your changes.