Home > Enterprise >  How to pass list object to html string?
How to pass list object to html string?

Time:09-11

The puzzle here that I am trying to solve is, how to show a list of items in another components as a string.html={listLocationsAsTextt} The end goal is to show that list each object in separate row as well. I am trying to use ReachTextFoldout component that needs html as string as it uses sanitized const sanitizedHTML = DOMPurify.sanitize(html, sanitizeConfig) . Could anyone see a way around this?

import React, { FC } from "react"
import * as S from "./styles/FeatureInfoStyles"
import * as T from "./types/FeaturedInfoTypes"

import RichTextFoldout from "components/molecules/richTextFoldout/RichTextFoldout"

const FeaturedInfo: FC<T.Props> = (p) => {
  const hasMoreThanThreeLocations = p.locations.length > 3

  const splitLocations = React.useCallback(() => {
    const maxLength = 3

    const firstThreeLocations = p.locations.slice(0, maxLength)
    const restLocations = p.locations.slice(maxLength, p.locations.length)

    return [firstThreeLocations, restLocations]
  }, [p.locations])

  const [firstThreeLocations, restLocations] = splitLocations()
  //Itterate trough the locations and create a list of them
  const idontbelievethis = (
    <ul>
      {restLocations.map((location: any) => (
        <li key={location}>
          {location.city}, {location.state}, {location.country}.
        </li>
      ))}
    </ul>
  )

  const listLocationsAsTextt = `${`<p><strong>${idontbelievethis}</p>`}`

  return (
    <S.View>
      {p.category && <S.Detail>{p.category}</S.Detail>}
      {p.experienceLevel && <S.Detail>{p.experienceLevel}</S.Detail>}
      {p.employmentType && <S.Detail>{p.employmentType}</S.Detail>}
      {hasMoreThanThreeLocations ? (
        <S.Header>
          {firstThreeLocations.map(
            (location: any, index: React.Key | undefined) => (
              <li key={index}>
                {location.city}, {location.state}, {location.country}.
              </li>
            )
          )}

          <RichTextFoldout
            html={listLocationsAsTextt}
            bgColor={""}
            height={0}
            maxHeight={10}
          />
        </S.Header>
      ) : (
        <S.Header>
          {firstThreeLocations.map(
            (location: any, index: React.Key | undefined) => (
              <li key={index}>
                {location.city}, {location.state}, {location.country}.
              </li>
            )
          )}
        </S.Header>
      )}
    </S.View>
  )
}

export default FeaturedInfo

CodePudding user response:

try this

import ReactDOMServer from 'react-dom/server';

// ...
const listLocationsAsText = ReactDOMServer.renderToStaticMarkup(
  <p>
    <strong>
      <ul>
        {restLocations.map((location: any) => (
          <li>
            {location.city}, {location.state}, {location.country}.
          </li>
        ))}
      </ul>
    </strong>
  </p>
);

  • Related