In my react application I have to pass an object to api end point like this:
{
"name": "string",
"description": "string",
"permissions": [
{
"name": "string",
"value": "string",
"groupName": "string",
"description": "string"
}
]
}
there are two text fields(for name and description) and and a checkbox(for permissions). If I checked the checkbox an object has to be push in permissions array and if I uncheck the checkbox array should be blank.
How do i do this? Please Help.
this is my codeblock:
import React, { useState, useEffect, Component } from 'react';
import TextField from '@material-ui/core/TextField';
import { Checkbox, FormControl, FormControlLabel, FormGroup, FormHelperText, FormLabel, Grid, makeStyles } from '@material-ui/core';
import Button from '@material-ui/core/Button';
export default class Index extends Component {
state = {
roleData: {
name: '',
description: '',
permissions: []
},
viewUser: false
}
handleSubmit = () => {
console.log(this.state.roleData);
}
handleViewUser = () => {
if (this.state.viewUser) {
this.state.roleData.permissions = [
{ data: 'abc' }
]
}
else {
this.state.roleData.permissions = [
{ data: 'xyz' },
{ newData: 'pqr' }
]
}
}
render() {
return (
<>
<TextField
name={this.state.roleData.name}
value={this.state.roleData.name}
onChange={e => { this.setState({ roleData: { ...this.state.roleData, name: e.target.value } }); }}
/>
<TextField
style={{ marginTop: '20px' }}
name={this.state.roleData.description}
value={this.state.roleData.description}
onChange={e => { this.setState({ roleData: { ...this.state.roleData, description: e.target.value } }); }}
/>
<FormControlLabel
control={<Checkbox
checked={this.state.viewUser}
onChange={e => { this.setState({ viewUser: e.target.checked }) }}
onClick={this.handleViewUser}
/>}
label="View User" />
<Button variant="contained" color="primary" style={{ marginTop: '20px' }} onClick={this.handleSubmit} > Submit </Button>
</>
)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…