Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found
Not Found

Submitted

Planet FAQs with dynamic asset importing

Tim 200

@animalchin45

Desktop design screenshot for the Planets fact site coding challenge

This is a solution for...

  • HTML
  • CSS
  • JS
3intermediate
View challenge

Design comparison


SolutionDesign

Solution retrospective


This challenge required me to learn about SVG importing and dynamically displaying SVG’s that are various sizes. While it is rather straight forward to import individual assets in a React project, this is a more difficult task when you have many assets. This is further compounded when you want to dynamically use said assets. I ended up with a couple of very useful hooks and a reusable SVG component that provided a more elegant solution. The result was much more reusable and easier to implement.

Also, in this project I modified the data.json file to add planet colors and SVG base sizes to aid in dynamically changing theme colors and correctly sizing planet graphics.

function importAll(r) {
  let images = {}
  r.keys().map((item) => {
    images[item.replace('./', '')] = r(item)
  })
  return images
}

export const images = importAll(
  require.context('../assets', true, /\.(png|jpe?g|svg)$/)
)
import { useRef } from 'react'

export default function useDynamicSVGImport(name) {
  const ImportedIconRef = useRef()
  ImportedIconRef.current = name

  return { SvgIcon: ImportedIconRef.current }
}
export default function Svg({ name, onCompleted, onError, ...rest }) {
  const { SvgIcon } = useDynamicSVGImport(name)

  if (SvgIcon) {
    return <SvgIcon {...rest} />
  }
  return null
}

Community feedback

Please log in to post a comment

Log in with GitHub
Discord logo

Join our Discord community

Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!

Join our Discord