'Reactjs - How use "return </Paper>" as code in my html?
I want to add into my code some tags <Paper> and </Paper>. But I didn't manage to do it. These two tags farmes my html code. But, when I runed my code, it show my them as string :
const test = () => {
const paperStyleTop = (nameMinistry) => {
if (nameMinistry === "justice"
) {
return `<Paper elevation={3} sx={{ ...(alertError && { border: "2px solid rgba(255,0,0,0.5)" }) }}>`
} else {
return `<Paper elevation={3}>`
}
}
const paperStyleBottom = () => {
return `</Paper>;`
}
const arrayMinistries = [
{
icon: "balance",
nameMinistry: "Justice",
id: "mJustice",
useStateFullName: ministers.justice.fullName
},
{
icon: "local_police",
nameMinistry: "Intérieur",
id: "mInterieur",
useStateFullName: ministers.interieur.fullName
}
]
return (
{arrayMinistries.map((ministry) => (
<Grid item}>
{paperStyleTop(ministry.nameMinistry)}
// Html code...
{paperStyleBottom()}
</Grid>
))}
)
export default test;
Could you explain to me how I can do to add these pieces of lines to my code ?
************** SOLUTION *************** With that propose below it dit like this and that work :
const test = () => {
const paperProps = (nameMinistry) => {
const props = {
elevation: 3,
};
if (nameMinistry === "mJustice" ||
nameMinistry === "mInterieur" ||
nameMinistry === "mEducationNationale" ||
nameMinistry === "mSante" ||
nameMinistry === "mArmees" ||
nameMinistry === "mEconomieFinance"
) {
props.sx = { ...(alertError && { border: "2px solid rgba(255,0,0,0.5)" }) };
} else {
props.sx = {}
}
return props;
}
const arrayMinistries = [
{
icon: "balance",
nameMinistry: "Justice",
id: "mJustice",
useStateFullName: ministers.justice.fullName
},
{
icon: "local_police",
nameMinistry: "Intérieur",
id: "mInterieur",
useStateFullName: ministers.interieur.fullName
}
]
return (
{arrayMinistries.map((ministry) => (
<Grid item}>
<Paper {...paperProps(ministry.id)}>
// Html code...
</Paper>
</Grid>
))}
)
export default test;
Solution 1:[1]
This sounds like an XY problem to me. It appears that you want to pass specific props into your <Paper> component: what don't you object spread the props dictionary into it instead?
You can use useMemo() to memoize the props you want to spread, so that the object will be updated based on changes in the dependency array.
Example:
const test = () => {
const paperProps = useMemo(() => {
const props = {
elevation: 3,
};
if (ministry.nameMinistry === 'justice') {
props.sx = { ...(alertError && { border: "2px solid rgba(255,0,0,0.5)" }) };
}
return props;
}, [ministry.nameMinistry])
return (
<Grid item>
<Paper {...paperProps}>
{/* More content here */}
</Paper>
</Grid>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Terry |
