M
M
Marcel Sultanov2020-02-14 14:36:40
JSON
Marcel Sultanov, 2020-02-14 14:36:40

How to create components from this JSON in React?

The JSON received from the server is given with the data for the web page. Based on this JSON, it is necessary to implement an adaptive layout of the page in React (in other words, use JSON as a source of data about the page).

How is it implemented? Can you give me a simple example?
did not work with JSON data yet
Link
https://gist.githubusercontent.com/alexandrov-va/7...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor Zhivagin, 2020-02-14
@Krasnodar_etc

In short, about the components array from json-a:
1) You make the components themselves, put them in a folder, conditionally, components
2) In components/index.js you write named exports of these components, the name of the exporter must match the type of objects in json -e. Example:

// index.js
export { default as GalleryComponent } from './GalleryComponent';
export { default as GridComponent } from './GridComponent';

3) You iterate over the array of components, at each iteration you "choose" by the type field which component to draw
import AllComponents from 'components/index'; // index можно не указывать, оставил для наглядности
....
// где-то в методе render:
const componentFromJson; // условно, это твой объект из JSON-a

const CurrentComponent = AllComponents[componentFromJson.type];
return (
  <CurrentComponent metadata={ componentFromJson.metadata } /> // пропс metadata только для примера, не забудь прокинуть остальные данные из JSON-a через пропсы
);

I think the method is clear, how to display sub-components for GridComponent you can figure it out yourself
Now about the form. You have an array fields. It needs to be split into two arrays main and additional, as far as I understand. And just output these arrays in two different blocks, through inputs.
You can try it yourself, if it doesn't work out - put your code in codesandbox and throw a link to it, it will be easier to help.

L
lasthead, 2020-02-14
@lasthead

And you have already made the classes of these components and you only dynamically add components? then I would look towards Higher-Order Components.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question