Daniel Bornstrand Daniel Bornstrand - 2 months ago 14
React JSX Question

Build react-router url from input

How do I add the value from the input field to the url string? In the example below

this.refs.foo
is
undefined
.

export class searchTest Component {
render() {
return (
<div>
<input ref="foo"/>
<Link to={`/stuff/${this.refs.foo.value}`}>
Find recipes!
</Link>
</div>
);
}
}

Answer

this.refs.foo does not exist on the first render, it is created after the first render. You need a safe default, perhaps by pulling out value into a variable before the return statement:

export class searchTest Component {
  render() {
    var value = this.refs.foo ? this.refs.foo.value : ''
    return (
      <div>
        <input ref="foo"/>
        <Link to={`/stuff/${value}`}>
          Find recipes!
        </Link>
      </div>
    );
  }
}

But even this won't work unless you have an onChange handler attached to the input. As you have it right now, searchTest will not re-render on an input change, so the prop passed to Link will not update. What you probably want is to keep foo's value in the state of searchTest, and have your Link be

<Link to={`/stuff/${this.state.foo}`}/>

instead of using refs.

Comments