Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to push react elements into an array using back ticks

I’m trying to push icons into an array by grabbing the name from data and simply adding: "<" and "/>" so that it becomes an Mui Icon.

I’ve renamed the imported icons to match the names in data but when I push them into my render array, all it renders is strings.

Any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addReaction } from "../features/postsSlice";

import ThumbsUp from "@mui/icons-material/ThumbUp";
import Happy from "@mui/icons-material/SentimentSatisfiedAlt";
import Sad from "@mui/icons-material/SentimentVeryDissatisfied";
import Heart from "@mui/icons-material/Favorite";
import Coffee from "@mui/icons-material/LocalCafe";
import { IconButton } from "@mui/material";

const Reactions = () => {
  const reactions = useSelector((state) =>
    Object.keys(state.posts[1].reactions)
  );
  const emojis = [];
  reactions.map((reaction) => {
    const capitalize = reaction[0].toUpperCase() + reaction.slice(1);
    emojis.push(<IconButton>{`<${capitalize} />`}</IconButton>);
  });
  console.log(emojis);
  return emojis;
};

export default Reactions;

>Solution :

You cannot use this way:

emojis.push(<IconButton>{`<${capitalize} />`}</IconButton>);

Instead what you can do is have an object map for all those:

// Create an object with all the possible elements you would use.
const MyMap = {
  ThumbsUp,
  Happy,
  Sad,
  Heart,
  Coffee
};

// And use it this way:
const EmojiElem = MyMap[capitalize];
emojis.push(<IconButton><EmojiElem /></IconButton>);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading