I have developed the Edit Notification page using react typescript. I get the notification title from the database and set that value into custom input component as follow
let notificationTitle: string = "Notification Test"; // getting from db
<FormInputText
label={"Notification Title:"}
value={notificationTitle}
name={`notificationTitle1`}
required={false}
placeholder={
"Text inside title tag - can include HTML text styles - bold, italic etc…"
}
labelClass={"full"}
/>
Full code link : https://codesandbox.io/s/zen-aryabhata-7lfch5?file=/src/EditPage.tsx
Issue:
but I can't update the input text box value and it keeps resetting to the default value passing from the database.
React TypeScript code.
Custom Input Component
import React, {useEffect, useState} from "react";
interface Props {
label: string;
name: string;
required? : boolean;
placeholder: string;
labelClass: string;
value?: string;
}
const FormInputText: React.FC<Props> = ({
label,name,required,placeholder,labelClass,rules,value
}) => {
console.log("FormInputText",value);
const [inputValue,setInputValue] = useState<string>("");
useEffect(() => {
if(inputValue == "" && value) {
setInputValue(value);
}else{
setInputValue(inputValue);
}
});
const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
setInputValue(e.target.value);
};
return (
<>
<label className={labelClass}>
<span>{label} {(required) ? <b>*</b> : <></>}</span>
<input type="text" onChange={changeHandler} name={name}
placeholder={placeholder} value={inputValue}/>
</label>
</>
);
}
export default FormInputText;
Edit Page
import "./styles.css";
import FormInputText from "./inputtext.component";
export default function EditPage() {
let notificationTitle: string = "Notification Test"; // getting from db
return (
<div className="App">
<h1>Edit Notification</h1>
<FormInputText
label={"Notification Title:"}
value={notificationTitle}
name={`notificationTitle1`}
required={false}
placeholder={
"Text inside title tag - can include HTML text styles - bold, italic etc…"
}
labelClass={"full"}
/>
</div>
);
}
CodePudding user response:
Your notificationTitle
is not a controlled element, from your EditPage
you need to pass this down to your FormInputText
component:
let notificationTitle: string = "Notification Test"; // getting from db
const [inputValue, setInputValue] = useState(notificationTitle);
Code here (Further improvement can be made)