skip to Main Content

I have a JSON file of recipes, and I am creating a React app using a specific flipbook library. The intricacies of that library aren’t really relevant, but I am creating its Page components dynamically from the JSON file.

Essentially, I want my JSON file to be able to hold html and CSS data such as <h3 className="class" Header!> and actually have that rendered in the dynamically generated Page components. Is this possible?

React page:

export default function RecipeBook() {
  const searchParams = useSearchParams();
  const book = useRef();
  const [pages, setPages] = useState([]);

  useEffect(() => {
    const recipeElems = Object.entries(recipes).map((element, i) => (
      // checks if page should be cover and/or if the page has a link to reference
      element[1].cover ? 
      <PageCover key={i} side={i%2==0 ? "L" : "R"}> {element[1].header} </PageCover>
      :
      element[1].link !== "" ? 
      <Page key={i} src={element[1].src} side={i%2==0 ? "L" : "R"} header={element[1].header}> 
      {element[1].content} Inspired by this <a href={element[1].link}>recipe.</a> 
      </Page> 
      :
      <Page key={i} src={element[1].src} side={i%2==0 ? "L" : "R"} header={element[1].header}> 
      {element[1].content}
      </Page> 
    ));
    setPages(recipeElems);
  }, [])  

  return (
    <div className="bookContainer">
      <HTMLFlipBook
      className="book"
      ref={book}
      width={350} height={450}
      maxWidth={350} maxHeight={450}
      size="stretch"
      maxShadowOpacity={0}
      >
        {pages}
      </HTMLFlipBook>
    </div>
  );
}

The JSON looks like this:

[
    {
        "header": "Desserts",
        "src": "",
        "cover": true
    },
    {
        "header": "Fl-Earl Gray Cake",
        "content": "Earl gray and marzipan-chunks sponge cake (1:1:1 b:s:f ratio, 3 eggs) soaked with çiçek suyu and rose syrup. n Rose cream cheese frosting. n Rose marmalade to decorate.",
        "link": "https://theclovecoterie.substack.com/p/nosferatu-cake",
        "src": "/kitchen/cake.jpg",
        "cover": false
    },
...
]

2

Answers


  1. You can just put the title in the "header" property like you did and then in your Page component, do something like this :

    <h3>{element.header}<h3>
    

    Also, no need to map through object entries. If your JSON recipes file is an array of objects like you provided here, you can map through each "element" without doing element[1]. Since each element is an object and not an array, you’ll get an error trying to index the object like that.

    Login or Signup to reply.
  2. You can do somthing like this:

    export default function App() {
    const example = { id: "my-class", href: "https://google.com" };
    
    return (
        <a className="class" {...example}>
            hi
        </a>
    );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search