Home > Net >  Map and Switch in React JSX
Map and Switch in React JSX

Time:02-21

I have a bit of a pickle, I have a React Function Component and i need to map and then switch inside my JSX.

I know i should attempt to do this outside/before the return statement but i can't seem to figure it out because the rendered component is dependent on an array passed through the component props.

Below is what i am trying to achieve inside my return statement

{(() => {
  files.map((file, index) =>
    let type = getFileType(file)
    switch(type){
      case 'image':
        return (
          <div className="item">
            <img src={file}/>
          </div>
        )
      default:
       return;
    }
  })()
}

I am obviously overlooking something important, i have been at it for a while and can't seem to get it. Any help will be appreciated.

CodePudding user response:

You need to return from the Immediate-Invoked Function. Try like below.

{(() => {
  return files.map((file, index) => {
    let type = getFileType(file);
    switch (type) {
      case "image":
        return (
          <div className="item">
            <img src={file} />
          </div>
        );
      default:
        return null;
    }
  });
})()}

CodePudding user response:

Something like this should work:

import React from "react";



const files = ["file01.img", "file02.other", "file03.img"];


const getFileType = (file) => {
    if (file.endsWith(".img")) return "image";
    return "other";
};



export default function YourComponent() {

    return (

        <div>

            { files.map( (file, index) => {
                
                let type = getFileType(file)
                
                switch (type) {
                    case 'image':
                        return (
                            <div className="item">
                                <p>image</p>
                            </div>
                        )
                    default:
                        return <p>other</p>
                }
                
            } )}

        </div>

    );

};
  • Related