Reputation: 3231
So im working on a React app, it's basically a CRUD app pretty much (serving right now as a learning practice project).
Anyways, I have a modal that appears when the user needs to edit some basic information on a resource (right now it's just a "name" that's being edited). The modal is a presentational/dumb component that takes in props from it's parent (Which is essentially just a table of the resources/items).
If im literally only going to be submitting the form to change 1 field I would only need a state with 1 item (for that input field to edit).......does it make sense to STILL make it a class just because it has a state? From what i've read if you have a state you should automatically make it a class?
Is this always true?
Upvotes: 1
Views: 374
Reputation: 9779
Are you talking like this?
When you click on any list item it goes to child(functional) component as you were asking.
You can check working live example Live demo
export default function App() {
const [arr, setArr] = useState(["One", "Two", "Three"]);
const [name, setName] = useState("");
const handleChange = e => {
setName(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
setArr([...arr, name]);
setName("");
};
return (
<div>
{arr.map(a => (
<div style={myStyle} key={a}>
{a} <button onClick={() => setName(a)}>Edit</button>
</div>
))}
<Child
handleChange={handleChange}
handleSubmit={handleSubmit}
name={name}
/>
</div>
);
}
const Child = ({ handleChange, name, handleSubmit }) => {
return (
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
};
const myStyle = {
margin: 5,
cursor: "pointer",
border: "1px solid lightgrey",
padding: "5px",
display: "flex",
justifyContent: "space-between"
};
Upvotes: 1
Reputation: 1834
Yes whenever you use a state you should make it a class (way back then) but now we have this thing called HOOKS that allows you to use states within functional components.
Simple sample implementation below.
import React, { useState } from 'react';
const Example = () => {
//creates a state name and a setter for it. Then initialize it with empty string
const [name, setName] = useState("");
return (
<div>
//suppose you have input here
<button onClick={() => setName("Your name value")}>
Click me
</button>
</div>
);
}
Upvotes: 1