'replace words in text with input values
in my app i map through the json and display a Paragraph, a component i create to show the title and the text. now my problem is that i also have a form and i want to update the shown text (which comes from json as props to paragraph) to replace the values in ${} to the corresponding value in the input. so for example if i change the name input i expect the name in the text i display to change in the same time. : i'm also using react hook form in this app. my json looks like this:
[
{
"title": "Article 1- Engagement",
"text": "Mme/M. ${nom, prénom} est engagé(e) au poste proposé par la société ${dénomination sociale} en qualité de ${qualification ou titre}. Ce contrat prend effet à compter du ${date effective} à ${heurs effective}."
},
{
"title": "Article II – Fonctions",
"text": "La société embauche le salarié à temps complet, en tant que ${dénomination de l’emploi}, avec la qualification professionnelle de ${qualification}, au coefficient (voir convention collective). Mme / M. ${nom, prénom} en sa qualité de ${poste occupé} sera plus particulièrement chargé de ${charge}."
}
]
```
```
import { Box, Heading, Text } from "@chakra-ui/layout";
import React from "react";
import { useFormContext } from "react-hook-form";
const Paragraph = ({ heading, text }) => {
const {
formState: { dirtyFields },
watch,
} = useFormContext();
const dirtyFieldsArray = Object.keys(dirtyFields);
const formValues = watch();
const fillTheBlanks = () => {
if (dirtyFieldsArray.length > 0) {
return dirtyFieldsArray.map((field) =>
text.replace("${" + field + "}", formValues[field])
);
}
return text;
};
return (
<Box pb="1">
<Heading as="h2" size="xs" fontSize="11" textAlign="left" pb="1">
{heading}
</Heading>
<Text>{fillTheBlanks()}</Text>
</Box>
);
};
export default Paragraph;
```
in my code i'm first getting the fields that the user is writing on. then map over them take the name of field to find the word to replace and then replace it with the value from the input. now this solution almost works but the text will repeat each time i change a new field.
i also tried to change this at the input lvl but the text only change once like i type e then he change the variable to e and no matter wt u type he wont change anymore, i guess that have to do with the replace function in js, like it lose track of wt word to change cause the word to replace changed...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
