Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda