For clean code & folder structure, I’m moving some data (in this case, modal data) to a separate file.
However, I’m not able to put a component inside an object value. Here’s what I want to do:
export function invalidId(id) {
return {
info: {
title: "Invalid ID!",
message: (
<>
The
<code className="inline-code">{id}</code>
is invalid. Please make sure blah blah blah...
</>
),
},
// I need help with this part
buttons: {
<>
<Button label="Retry" />
<Button label="More Info" >
</>
}
}
}
import { invalidId } form "modaldata";
setModalInfo(invalidId(id).info);
setModalButtons(invalidId(id).buttons);
I used return here because id is dynamic. The main problem is buttons part. What is the correct way to put JSX inside an object?
>Solution :
Remember that a JSX expression results in an object value (it gets converted into a call to React.createObject(/*...*/) or whatever else is set up as the JSX function). Like any other value, if you want to put that value inside an object, you either need to:
-
Just use the fragment directly (not within another object); or
-
Use a property name (or names); or
-
Use an array
(Or make buttons a function that returns the fragment, as abhi patil shows.)
Here’s #1 (note no {}):
buttons: <>
retry: <Button label="Retry" />
moreInfo: <Button label="More Info" >
</>
Here’s #2, assuming you want separate property names for the two buttons:
buttons: {
retry: <Button label="Retry" />,
moreInfo: <Button label="More Info" >,
}
Here’s #3, an array (rather than plain object) containing the two buttons:
buttons: [
<Button label="Retry" />,
<Button label="More Info" >,
]