Home > front end >  How to export react jsx component in an object?
How to export react jsx component in an object?

Time:01-08

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?

CodePudding user response:

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" >,
]

CodePudding user response:

You need to return the jsx template in a object field and call it like a function.

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" >
         </>   
      )
   }
}

setModalButtons(invalidId(id).buttons();
  •  Tags:  
  • Related