Home > Enterprise >  access imported tag from array in react
access imported tag from array in react

Time:04-20

I would like to access a tag that is imported into an array.

{files[1]} is not displaying anything. The only way to display the imported tag is to use the normal declaration: <FileOne/>

This is what I tried to do:

const FileOne = (
  () => {
    return 
      <div>FileOne</div> 
    )
  }
)

export default FileOne;
import FileOne from "./Files/FileOne";
import FileTwo from "./Files/FileTwo";

const files = [FileOne, FileTwo];

export default function FilesPage() {
  return (
    <div>
      <FileOne/> {/* works */}
      {files[1]} {/* doesn't work */}
    </div>
  )
}

CodePudding user response:

This should work if you define your array to have JSX elements and not the function:

const files = [<FileOne/>, <FileTwo/>]

export default function FilesPage() {
  return (
    <div>
      {files[0]}
      {files[1]}
    </div>
  )
}

CodePudding user response:

Typo

First of, you have an incorrect ( in your declaration of FileOne. It should be this:

const FileOne = (
  () => {
    return 
      <div>FileOne</div> 
  }
)

and even then I am not sure if that is really what you want. Shouldn't it be more like this:

const FileOne = () => {
  return <div>FileOne</div>;
};

Solution

As the variables in your files array are functions, you have to call them. So it should be like this:

export default function FilesPage() {
  return (
    <div>
      <FileOne/> {/* works */}
      {files[1]()} {/* works now */}
    </div>
  )
}

Check out this codepen for a working demo.

  • Related