I am trying to print the value of input on the screen, but it keeps updating every time I enter a new character.
/*Import*/
import React, { useState } from "react";
import "./Search.scss";
/*Component*/
const Search = () => {
/*State*/
const [input, setInput] = useState("");
/*On Form Submit*/
return (
<>
<div className="Search">
<form onSubmit={(e) => e.preventDefault()} className="Search__form">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
type="text"
placeholder=" Title, companies, expertise, or benefits"
style={{ fontFamily: "Arial, FontAwesome" }}
></input>
<button onclick={console.log(input)}>Search</button>
</form>
<h1>{input}</h1>
</div>
</>
);
};
/*Exprting*/
export default Search;
I just want to print the whole value after I click the button
You are calling console.log(input) on each rerender instead of only on click. Convert it to an arrow function and it should do what you want.
<button onClick={()=>console.log(input)}>Search</button>
EDIT: To answer your follow-up question: You need two separate state variables:
/*Import*/
import React, { useState } from "react";
import "./Search.scss";
/*Component*/
const Search = () => {
/*State*/
const [input, setInput] = useState("");
// new state variable
const [submittedInput, setSubmittedInput] = useState("");
/*On Form Submit*/
return (
<>
<div className="Search">
<form onSubmit={(e) => e.preventDefault()} className="Search__form">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
type="text"
placeholder=" Title, companies, expertise, or benefits"
style={{ fontFamily: "Arial, FontAwesome" }}
></input>
<button onClick={()=>setSubmittedInput(input)}>Search</button>
</form>
<h1>{submittedInput}</h1>
</div>
</>
);
};