'Text input field won't submit when pressing enter
I have a text input that I am trying to use to create new tags
via hooks. However, when I enter in the value and press enter, nothing happens. I Googled it and was told to make the input type=text
but this has not fixed it. Here is the code:
import React, { useState } from 'react';
import AddIcon from '@mui/icons-material/Add';
import MaximizeIcon from '@mui/icons-material/Maximize';
import './styles.css';
const Card = ({ id, pic, name, email, company, skill, average, grades }) => {
const [clicked, setClicked] = useState(false);
const [tags, setTags] = useState([]);
return (
<div className='card' id={id}>
<img src={pic} alt='avatar' className='img' />
<div className='list'>
<h1>{name}</h1>
<div className='properties'>
<p>Email: {email}</p>
<p>Company: {company}</p>
<p>Skill: {skill}</p>
<p>Average: {average}</p>
</div>
<input
type='text'
placeholder='Add a tag'
onSubmit={(e) => {
setTags(...tags, e.target.value);
console.log(tags);
}}
/>
{clicked && (
<div className='grades'>
{grades.map((grade, index) => (
<p>{`Test ${index}: ${grade}%`}</p>
))}
</div>
)}
</div>
<button onClick={() => setClicked(!clicked)}>
{!clicked ? (
<AddIcon fontSize='large' />
) : (
<MaximizeIcon fontSize='large' />
)}
</button>
</div>
);
};
export default Card;
How do I make it submit a new tags
to the setTags
hook?
Solution 1:[1]
You can use keyDown Event
onKeyDown = {
(e) => {
if (e.key === 'Enter') {
setTags(...tags, e.target.value);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Heet Vakharia |