I am messing around with Riot's API that allows getting information of a player by the player's name, I am trying get API key(I know it's stupid but I only got a 24 hours key) and the target player's name from users' input.
export function PlayerSearch() {
function handlesubmit(e) {
console.log(e.target);
e.preventDefault();
}
return <div className='player'>
<div className='inputfield'>
<form onSubmit={handlesubmit} method='GET' autoComplete="off">
<div>
<label htmlFor="key">Your API key:</label>
<input placeholder='Your API key' onFocus={(e)=>{e.target.placeholder=''}} type="text" id="key" name="key" />
</div>
<div>
<label htmlFor="name">Player name:</label>
<input placeholder='Player name' onFocus={(e)=>{e.target.placeholder=''}} type="text" id="name" name="name" />
</div>
<div>
<input type='submit' />
</div>
</form>
</div>
</div>
}
And I got this in the console:
So how exactly do I extract the two inputs from the form?
In addition, is it possible that I can call another component and pass data as props to handle the submitted data so that the code is cleaner?
CodePudding user response:
You should have a state to store your inputs:
const [formData, setFormData] = useState({ key: "", name: "" });
Then you need a function that gets called onChange
of your input fields to update your state:
const onChange = (event) => {
setFormData({ ...formData, [event.target.name]: event.target.value });
};
And you need to pass that function to your input
onChange
property:
<input
placeholder="Your API key"
onFocus={(e) => {
e.target.placeholder = "";
}}
type="text"
name="key"
value={formData.key}
onChange={onChange}
/>
Then you can access the state in your handleSubmit
:
function handlesubmit(e) {
console.log(formData);
e.preventDefault();
}