I have a textarea that already show some json string. And I can edit directly on it. But when I trigger onChange and update value of textarea it's not json form anymore and I got the error. So I don't know how I can do properly.
More explain:
textarea showing
{
"Id":1,
"Action":"CONCAT",
"Targets":["eval(\"","link=\\\"","$Link","\\\";sp=link.split(\\\"__requestHeader=\\\");sp[0]\")"],
"Result":"$str_Link"
}
And I try to delete "Result" out of it but When I delete Quotation mark make Its not Json anymore, show I can't delete anymore.
codesanbox: https://codesandbox.io/s/infallible-mendeleev-6641iw?file=/src/App.js:0-1079
import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
const [value, setValue] = useState([
{
Id: 1,
Action: "CONCAT",
Targets: [
'eval("',
'link=\\"',
"$Link",
'\\";sp=link.split(\\"__requestHeader=\\");sp[0]")'
],
Result: "$str_Link"
},
{
Id: 2,
Action: "CONCAT",
Targets: [
'eval("',
'link=\\"',
"$Link",
'\\";sp=link.split(\\"__requestHeader=\\");sp[1]")'
],
Result: "$str_Header"
}
]);
const valueHandleChange = (e, index) => {
let newValue = [...value];
newValue[index] = JSON.parse(e.target.value);
setValue(newValue);
};
return (
<div className="App">
{value.map((item, index) => {
return (
<textarea
spellCheck={false}
onChange={(e) => valueHandleChange(e, index)}
value={JSON.stringify(item, null, "\t")}
></textarea>
);
})}
</div>
);
}
CodePudding user response:
You can do like below. I think we can ignore the react warning(not an error) as this is a special case.
const valueHandleChange = (e, index) => {
try {
let newValue = [...value];
newValue[index] = JSON.parse(e.target.value);
setValue(newValue);
} catch (err) {
//any operation can be performed here
console.log(err);
}
};
return (
<div className="App">
{value.map((item, index) => {
return (
<textarea
spellCheck={false}
onChange={(e) => valueHandleChange(e, index)}
rows="20"
cols="50"
key={index}
>
{JSON.stringify(item, null, "\t")}
</textarea>
);
})}
</div>
);
https://codesandbox.io/s/stackoverflow-6u05e7?file=/src/Validation/JsonValidation/JsonValidation.js