Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs: implementing dangerouslySetInnerHTML inside a functional component

Tags:

reactjs

I have been trying to figure out how to apply dangerouslySetInnerHTML to this label={item.description} inside of this component:

const SwitchList = ({
  color,
  disabled,
  sortKey,
  sortDirection = SORT_DIRECTION.ASC,
  items,
  data,
  children,
  onChange
}) => {
  if (items.length === 0) {
    return React.Children.only(children);
  }
  let sortProp = null;
  let sortedItems = items;
  if (sortKey) {
    sortProp = new SortProperty(sortKey, sortDirection === SORT_DIRECTION.ASC);
    sortedItems = items.sort(genericObjectSort(sortProp));
  }
  return (
    <div>
      {sortedItems.map(item => {
        return (
          <Switch
            checked={data[item.key]}
            label={item.description}
            onChange={onChange(item.key)}
            key={item.key}
            color={color}
            disabled={
              typeof disabled === "function" ? disabled(item) : disabled
            }
            className={styles.customSwitch}
          />
        );
      })}
    </div>
  );
};
SwitchList.propTypes = {
  sortKey: PropTypes.string,
  sortDirection: PropTypes.number,
  items: PropTypes.arrayOf(PropTypes.object),
  data: PropTypes.object,
  children: PropTypes.node,
  color: PropTypes.string,
  disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
  onChange: PropTypes.func
};

export default SwitchList;

A helper function will not help because this is not a class-based component.

How can I take that {items.description} and apply dangerouslySetInnerHTML inside a functional component?

like image 908
Daniel Avatar asked Sep 17 '25 12:09

Daniel


1 Answers

Try this:

<Switch
            checked={data[item.key]}
            label={<span dangerouslySetInnerHTML={{__html:item.description}}></span>}
            onChange={onChange(item.key)}
            key={item.key}
            color={color}
            disabled={
              typeof disabled === "function" ? disabled(item) : disabled
            }
            className={styles.customSwitch}
          />

Or

label= {<span className="content" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(item.description) }}></span>}
like image 198
Bhawana Avatar answered Sep 20 '25 04:09

Bhawana