Home > Back-end >  How to add an if-else statement in react to read json-schema?
How to add an if-else statement in react to read json-schema?

Time:12-07

I am very new to js and react so I hope that someone can give me an idea for this problem. My solution is very bad but I couldn't come up with a good solution. I don't know either how to add if-else statement in render. There are 6 buttons and each button is a name of a json-schema(it should be better to have a table instead of buttons but I get errors all the time with tableview). I want to show json-schema, when user clicks a button so that the user can submit a json file.

import React, { Component, useState } from 'react';
import { Row, Col } from 'react-bootstrap';
import { withTheme } from '@rjsf/core';
import schema1 from '../schemas/schema1.json';
import schema2 from '../schemas/schema2.json';
import { Datagrid, TextField, EditButton, DeleteButton } from 'react-admin';

class MyApp extends Component {

    constructor(props) {
        super(props);
        this.clickme = this.clickme.bind(this);
    }
    

    ToggleGroup() {
        const theme = {
            blue: {
                default: '#3f51b5',
                hover: '#283593',

            },
            pink: {
                default: '#000000',
                hover: '#ad1457'
            }
        }
        



        
          
        return (<div>
            {types.map(type => (

                <Col>
                    <Col>
                        <Button
                            active={active === type}
                        >{type}</Button>
                    </Col>
                </Col>
            ))}
            <Col>
           <Form
            schema={schema1}     
          
          />
          </Col>
        </div>
        );
    }

    render() {
        return (
            <>
                <Col>
                    <Col>
                        <text>
                            List of schemas
                        </text>
                    </Col>
                </Col>
                <this.ToggleGroup />

            </>
        );
    }
}


export default MyApp;

CodePudding user response:

Your issue seems to be mostly with how to structure your code. This is something you can best learn by studying the code of other people. This github repository contains a lot of great bits and pieces to help you out.

To answer your question, I would recommend you to separate your components. The solution might become clear to you by itself. Maybe you can add your schemas to an object / map and then select the schema based on the activeType that you select within your ToggleGroup.

E.g.:

import schema1 from '../schemas/schema1.json';
...

const schemas = new Map([
  ['schema1', schema1],
  ['schema2', schema2],
  ...
]);

// In your Form-Component

const activeSchema = schemas.get('activeType')
  • Related