Home > Back-end >  React put query string into form's value attribute
React put query string into form's value attribute

Time:12-07

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

CodePudding user response:

I would suggest you get the value of the search-param when the component mounts, and store it in the component's local state. Then read/update the value from state. Something like:

const [search, setSearch] = useState("");

useEffect(() => {
    setSearch(new URLSearchParams(new URL(window.location.href).search).get('q'));
}, []);

return (
     <intput type="text" value={search} onChange={e => setSearch(e.target.value)} />
);

I've not tested it, but you get the gist of it.

CodePudding user response:

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;

CodePudding user response:

It would be easier to provide a more concrete answer if you share the code or gist

  • Related