Search code examples
javascriptreactjsreact-component

Display React component without knowing its structure


I am still relatively new to the React and I am having problem with approach I should follow. I want to create an app that fetches a JSON object every time I refresh the page. Every JSON object has a unique structure - there is a title and a heading included in every post but each of the blog-posts can also consist of images, paragraphs and unordered/ordered lists - some might have multiple images but no paragraphs, there might be one that has no images nor paragraphs just 7 lists, some might have all three elements etc.

Only these 5 elements are allowed but the order and occurrence is basically random every time. There is my question - how can I make the app display every element of the blog-post regardless of its type?


Solution

  • For every of 5 elements you can create React component. After it in you Blog component import all of this components. In render method you can go through JSON from API and call custom function renderComponent(componentName), where componentName is taken from JSON. In renderComponent you can use switch case to decide which React component should be returned. It's pretty naive implementation but a way to start