javascriptreactjsformsvirtual-dom

React put query string into form's value attribute


I have a search page, something/search?q=foo, whenever im at this page I want to put foo in my form's value tag. (Not for search purposes, I have a fully functioning search bar, I just want to show the client the last thing he searched for).

I've gotten the search term with: (window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : '', this works, although when putting it into the forms value tag, react blocks immediately, it doesn't let me write anything into the input field. I think this is because it updates to this string super fast and you don't see it happening.

How would I achieve this, to update my form's value one time and thats it?

Here is my simplified code:



<input type="search" name="q" id="q" value={(window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : ''} <--- This is where I want to put the search string

What i've tried so far is this:


this.state = {
   value:''
}

...

handleTitle = (s) => {
   this.setState({value:s})
}

...

<input ... value={this.state.value} onChange={this.HandleTitle((window.location.href.indexOf("?q") != -1) ? window.location.href.substring(window.location.href.indexOf("?q") + 3) : '')}

this results in infinite state updates


Solution

  • Anyway if you want to access the q natively. Working example https://8zwht.csb.app/?q=test

    import React from "react";
    import "./styles.css";
    
    class App extends React.Component {
      state = {
        value: ""
      };
    
      componentDidMount() {
        const search = new URL(window.location).searchParams;
        const term = search.get("q");
        if (term)
          this.setState({
            value: term
          });
      }
    
      handleChange = (e) => {
        this.setState({
          value: e.target.value
        });
      };
    
      render() {
        return (
          <input
            type="text"
            onChange={this.handleChange}
            value={this.state.value}
          />
        );
      }
    }
    export default App;