I am react beginner and I would like to create 2 inputs for first and last name.
When i call <Item/> the focus on input disappears after typing one character, but when i call {Item()} everything works fine as expected. It looks like some strange behavior to me and my question is why? Any ideas?
const { useState } = React;
function Item() {
const [firstName, setFirstName] = useState("John");
const [lastName, setLastName] = useState("Rambo");
function HandleFirstNameChange(event) {
setFirstName(event.target.value);
}
function HandleLastNameChange(event) {
setLastName(event.target.value);
}
// display
function Display(props) {
return (
<div>
{firstName}, {lastName}
</div>
);
}
// edit
function Edit(props) {
return (
<div>
<form>
<input
type="text"
value={firstName}
onChange={HandleFirstNameChange}
/>
<input type="text" value={lastName} onChange={HandleLastNameChange} />
</form>
</div>
);
}
return (
<div>
<Display />
{/* here after typing one character focus of input disappears */}
<Edit />
{/* here everything works fine as expected */}
{Edit()}
{/* whyyyy?? */}
</div>
);
}
ReactDOM.render(<Item />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
This is because you are defining the Edit component inside the Item component and so on every render, Edit function will be defined again and because of that react will try and replace it in the DOM tree on every render.
When you are calling the function, you are not actually using the Edit function as a React component. The below code will work just fine.
import React, { useState } from "react";
// display
function Display(props) {
const { firstName, lastName } = props;
return (
<div>
{firstName}, {lastName}
</div>
);
}
// edit
function Edit(props) {
const {
firstName,
HandleFirstNameChange,
lastName,
HandleLastNameChange
} = props;
return (
<div>
<form>
<input type="text" value={firstName} onChange={HandleFirstNameChange} />
<input type="text" value={lastName} onChange={HandleLastNameChange} />
</form>
</div>
);
}
function Item() {
const [firstName, setFirstName] = useState("John");
const [lastName, setLastName] = useState("Rambo");
function HandleFirstNameChange(event) {
setFirstName(event.target.value);
}
function HandleLastNameChange(event) {
setLastName(event.target.value);
}
return (
<div>
<Display firstName={firstName} lastName={lastName} />
{/* here after typing one character focus of input disappears */}
<Edit
firstName={firstName}
lastName={lastName}
HandleFirstNameChange={HandleFirstNameChange}
HandleLastNameChange={HandleLastNameChange}
/>
</div>
);
}
export default Item;