Home > Software engineering >  How to modify this to not be two components in React
How to modify this to not be two components in React

Time:09-11

NOTE: I HAVE REPLACED THIS QUESTION WITH ONE WITH MORE CLARITY AT THE LOCATION: Context not returned when referencing React component as function instead of JSX

I WOULD LIKE TO DELETE THIS BUT SO WILL NOT LET ME.

I have the following JavaScript file that is one React component calling another one nested inside it. I want to change this to not use the name of the nested component but instead create the internal component as an anonymous one.

I want to usr the JavaScript name and not return JSX.

Here is my original working component

const InsideComponent = () => {
 
  return (
    <div>
      Inside Component
    </div>
  );
};

export default function Speakers() {
  return (
    <div>
      <InsideComponent />
    </div>
  );
}

I've tried a few combinations including this below that do not work

export default function Speakers() {
  return (
    <div>
      { 
         return (
           { InsideComponent()}
         )
      }
    </div>
  );
}

CodePudding user response:

Using { inside the context of JSX stops the JSX syntax and begins a plain JavaScript expression. (Not a function - no return.) So from here

    <div>
      { 

for the syntax to be valid, you'd need to have an expression that evaluates to a JSX element:

export default function Speakers() {
  return (
    <div>
      { 
         (
           <div>
             Inside Component
           </div>
         )
      }
    </div>
  );
}

But the nesting of a JavaScript expression isn't useful at all there - better to just insert the plain JSX instead.

export default function Speakers() {
  return (
    <div>
      <div>
        Inside Component
      </div>
    </div>
  );
}

CodePudding user response:

When you want to merge components, you just need to merge the JSX portion of it.

In your example, you can just do

export default function Speakers() {
  return (
    <div>
      <div>
         Inside Component
      </div>
    </div>
  );
}

CodePudding user response:

Why not this?

export default function Speakers() {
  return (
    <div>
      <div>
        Inside Component
      </div>
    </div>
  );
}

Unless you're using the InsideComponent as part of other components, there is no need to separate the two. But if you want to, just use it like you would any other component.

export default function Speakers() {
  return (
    <div>
      <div>
        <InsideComponent />
      </div>
    </div>
  );
}

CodePudding user response:

export default function Speakers() { return ( Inside Component ); }

Isn't this is what you are looking for?

  • Related