React dynamic layout based on JSON file

225
January 12, 2018, at 05:01 AM

While designing my ReactJS app I have a question with dynamic layout implementation (of my reading/news app) based on JSON file. For now it's got to be only Main page (including listing of articles) and detail page for articles.

Let's say that I have endpoint that is serving JSON file with list of contents for every article (titles, leads, links, photo(s), component name) that is meant to be displayed on main page. For that I've got few different React components - not only for visual purpose but also for display readers, SEO etc. - that combined together are forming Main page.

So while iterating on got JSON, how can I fire particular React component to show every single article based on component name set in this JSON?

Answer 1

Your solution is to iterate over the json in render() method, then for each object that abstract a component, you will map a real component, based on this data. For example:

render() {
    const { data } = this.props;
    {data && data.map( componentData => {
            switch(componentData.type) {
                    case TYPE1:
                        return <Type1 {...componentData} />
                     // then handle other types
             }
        })}
}

Of course, if your switch/case is too long, you can simply export it to some helper method for cleaner render()

READ ALSO
Build tree structure in html using json

Build tree structure in html using json

I'm trying to build a dynamic tree structure in htmlI'm getting result from database in nested json format

264
React Native TextInput different background colors for different letters/characters?

React Native TextInput different background colors for different letters/characters?

I know I can set the background for a TextInput, but I want to change the background color of parts of the TextInput to highlight certain letters

299
Dropzone.js uploading Base64 strings

Dropzone.js uploading Base64 strings

I'm using a javascript plugin Dropzonejs to help make my uploading seems seamless to the user

947