Search code examples
reactjsaxiosrendering

display icon based on file type


I want to display icons based on the file type. From the object that I am fetching from strapi I can get the file extension. But I want to render it dynamically on the table.

const TableData = () => {
  const [data, setData] = useState([]);

  const getData = () => {
    axios.get("http://localhost:1337/document-uploads").then((response) => {
      console.log(response);
      const myData = response.data;
      setData(myData);
    });
  };

  useEffect(() => getData(), []);

  return (
    <div className="my-5">
      <Table striped bordered hover>
        <thead>
          <tr>
            <th>Icon</th>
            <th>File Name</th>
            <th>Description</th>
            <th>Author</th>
            <th>Date created</th>
          </tr>
        </thead>
        <tbody>
          {data &&
            data.map((file: File) => (
              <tr key={file.id}>
                <td>
                  {() => {
                    if (file.document.ext == ".pdf") {
                      return <img src={PDF} />;
                    } else if (file.document.ext == ".xml") {
                      return <XML />;
                    } else {
                      return <JPEG />;
                    }
                  }}
                </td>
                <td>{file.document.name}</td>
                <td>{file.description}</td>
                <td>{file.author}</td>
                <td>{file.created_at}</td>
              </tr>
            ))}
        </tbody>
      </Table>
    </div>
  );
};

export default TableData;

I am getting the error: "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it."


Solution

  • You can try the code without the anonymous function inside, just start from the if statement without everything wrapped inside a function.

                       {
                        if (file.document.ext == ".pdf") {
                          return <img src={PDF} />;
                        } else if (file.document.ext == ".xml") {
                          return <XML />;
                        } else {
                          return <JPEG />;
                        }
                      }
    

    You can as well try different approaches with more modern javascript and ternary operators:

                       {
                        file.document.ext == ".pdf" ? <img src={PDF} /> : 
                        file.document.ext == ".xml" ? <XML /> : <JPEG />
                       }
    

    Which is the same as the first code block.