'React input text box loses focus after typing a character
I see this is a common question but can't figure out the solution from the other answers because they don't follow the same process I have. This is a follow on to my original question: useState variable not holding its state during onChange event.
Basically every time I type a character the popUp is re-rendering causing the input box to lose focus.
const App() {
const [units, setUnits] = useState('');
const [showPopUp, setShowPopUp] = useState(false);
const [teamState, setTeamState] = useState(null);
const [lineState, setLineState] = useState(null);
...
function PopUp() {
return (
<div id="popUp" className={popUpStyle}>
<div className="pop-up-bg"> </div>
<div className="pop-up">
<img className='close-button' src={closeButton} onClick={hpu} />
{teamState && lineState && betslip(teamState, lineState)}
</div>
</div>
)
}
function handleChange(event) {
setUnits(event.target.value)
}
const betslip = (team, line) =>
(
<div className='betslip'>
<h1 className="betslip-header">Betslip</h1>
<div >
<table className="betslip-table">
<tr>
<th>Team</th>
<th>Line</th>
<th>Unit(s)</th>
</tr>
<tr >
<td className='betslip-td'>{team}</td>
<td className='betslip-td'>{linePlusMinus(line)}</td>
<td className='betslip-td'>
<div className='unit-div'>
<input type='text' className='unit-input' onChange={e => setUnits(e.target.value)} value={units}/>
</div>
</td>
</tr>
</table>
<table className="betslip-table">
<tr>
<th>Risk</th>
<td className='betslip-td'>{units}</td>
</tr>
<tr>
<th>Reward</th>
<td className='betslip-td'>{reward(units, line)}</td>
</tr>
</table>
</div>
</div>
);
function spu(team, line){
setTeamState(team);
setLineState(line);
setPopUpHtml(betslip(teamState, lineState));
setShowPopUp(true);
}
function hpu(){
setShowPopUp(false);
}
...
return(
<div className="container">
{ showPopUp && <PopUp />}
...
)}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
