Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to export react jsx component in an object?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

  1. Just use the fragment directly (not within another object); or

  2. Use a property name (or names); or

  3. 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" >,
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading