Code duplication: how to avoid in Reactjs

74 Views Asked by At

Expectation: if the flag is true, then empty div "container" around div "content"

const Demo = () => {
   const [flagABC] = useFlagFeature(true)
   return (
     <div className="featureflagoff"> style= {} onMouseEnter = {}  //if feature flag is off || if feature flag is ON then empty div  
       <div className="content">           
          // huge code
       <div>
     </div>
   );
}

how can i avoid copying the ("huge code") twice.

2

There are 2 best solutions below

0
On BEST ANSWER

Assign the huge code to a variable and reference it.

const hugeCode = <div>...</div>

return (
  <div className="featureflagoff">
    <div className="content">           
      {hugeCode}
    <div>
  </div>
);

2
On

Assuming flagABC is the flag, you can do something like this:

const Demo = () => {
   const [flagABC] = useFlagFeature(true)
   return (
     <div className={flagABC ? "" : "featureflagoff"}>
       <div className="content">           
          // huge code
       <div>
     </div>
   );
}