Modify the data in a set of text boxes

I have a component that consists of a form:

import React from 'react'
import Relay from 'react-relay'

import { browserHistory } from 'react-router'

import MenuItem from 'material-ui/MenuItem'
import TextField from 'material-ui/TextField'

import CreateTransformationSetMutation from '../mutations/CreateTransformationSetMutation'

class CreateTransformationSetDialog extends React.Component {

  componentWillMount() {
    this.props.setOnDialog({
      onSubmit: this.onSubmit,
      title: 'Create and Apply Transformation Set'
    })
  }

  initial_state = {
    targetTableName: '',
    transformations: this.props.viewer.version.columns.edges.map(edge => edge.node).map(column => {
      return {
        targetColumnName: column.name, 
        ruleExpression: '{{' + column.name + '}}'
      }
    })
  }

  state = this.initial_state

  onSubmit = () => {
    const onSuccess = (response) => {
      browserHistory.push('/table')
    }

    const onFailure = () => {}

    Relay.Store.commitUpdate(
      new CreateTransformationSetMutation(
        {
          viewer: this.props.viewer,
          version: this.props.viewer.version,
          targetTableName: this.state.targetTableName,
          transformations: JSON.stringify({transformations: this.state.transformations}),
        }
      ),
      { onSuccess: onSuccess }
    )
  }

  handleTableNameChange = (e) => {
    this.setState({
      targetTableName: e.target.value
    })
  }

  handleTransChange = (e) => {

    ////what should go here////

  }

  render() {
    return (
      <div>
        <TextField
          floatingLabelText="Table Name"
          value={this.state.targetTableName}
          onChange={this.handleTableNameChange} 
        />
        <br />
        {
          this.props.viewer.version.columns.edges.map((edge) =>
            <div key={column.id}>
              <TextField
                name="targetColumnName"
                floatingLabelText="Target Column"
                value={this.state.transformations[i].targetColumnName}
                onChange={this.handleTransChange}
                style={{ margin: 12 }} 
              />
              <TextField
                name="ruleExpression"
                floatingLabelText="Rule to Apply"
                value={this.state.transformations[i].ruleExpression}
                onChange={this.handleTransChange}
                style={{ margin: 12 }}
              />
            </div>
          )
        }

      </div>
    )
  }

}

export default Relay.createContainer(CreateTransformationSetDialog, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        ${CreateTransformationSetMutation.getFragment('viewer')}
        version(id: $modalEntityId) @include(if: $modalShow) {
          ${CreateTransformationSetMutation.getFragment('version')}
          id
          name
          columns(first: 100) {
            edges {
              node {
                id
                name
              }
            }
          }
        }
      }
    `
  },
  initialVariables: {
    modalEntityId: '',
    modalName: '',
    modalShow: true,
  },
  prepareVariables: ({ modalEntityId, modalName }) => {
    return {
      modalEntityId,
      modalName,
      modalShow: modalName === 'createTransformationSet'
    }
  }
})

Every input in the form includes two material-ui TextFields with default values fetched from this.state.transformations. However, I'm facing issues trying to update these field values.

The default state of transformations is like:

transformations: [
  {targetColumnName: 'ID', ruleExpression: '{{ID}}'},
  {targetColumnName: 'First Name', ruleExpression: '{{FirstName}}'},
  {targetColumnName: 'Last Name', ruleExpression: '{{LastName}}'}
]

And I aim to modify it so that the state can be updated as follows:

transformations: [
  {targetColumnName: 'ID', ruleExpression: '{{ID}}'},
  {targetColumnName: 'First Name', ruleExpression: '{{FirstName}}'},
  {targetColumnName: 'Percentage', ruleExpression: '{{Percentage/100}}'}
]

The form utilizes Relay, but that's not pertinent to this inquiry.

Your assistance with this matter would be greatly valued.

Thank you for your attention.

Answer №1

I encountered a similar issue and decided to assign the value to the value attribute, utilizing defaultValue='some-value' for flexibility in mutation and alteration.

It appears that achieving what you intend may not be feasible in order to prevent XSS (Cross-site scripting)

You can structure it like this:

<TextField
  name="targetColumnName"
  floatingLabelText="Target Column"
  defaultValue={this.state.transformations[i].targetColumnName} {/* switching from value to defaultValue */}
  onChange={this.handleTransChange}
  style={{ margin: 12 }} 
/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering type errors in React+Typescript while dynamically setting values in the change handler

I am currently working on dynamically generating a form based on an array of objects. The objective is to allow users to create accounts dynamically by clicking the Add User button and then submit the complete state object of users to the backend. Encoun ...

create-react-app : npm ERROR! JSON data parsing halted unexpectedly near '....'

Explain the issue The command npx create-react-app my-app is not functioning properly. I have attempted to resolve the problem by using npm cache clean --force, but unfortunately, I continue to encounter the same error repeatedly. Steps for replication ...

What causes a statically generated page to appear without any style when transmitted to the client?

After setting up the Next.js official boilerplate with npx create-next-app and opening it in the browser, I observed that the static HTML document lacks styling: https://i.stack.imgur.com/mna6K.png I am concerned about potential FOUC issues. How can I en ...

Is it necessary for me to generate a fresh component within the React iteration?

Imagine we have a list of contacts to display Alice - 123 Ben - 487 ... Emily - 034 The dilemma is whether to implement it all in one ContactList component function ContactList (props) {    return (      <div>        {props.contacts.ma ...

React Weather App: difficulties entering specific latitude and longitude for API requests

I have successfully developed an app that displays the eight-day weather forecast for Los Angeles. My next objective is to modify the longitude and latitude in the API request. To achieve this, I added two input fields where users can enter long/lat values ...

How can we use SWR to fetch user data conditionally based on their logged-in state?

I am facing an issue with setting the UI state based on whether a user is logged in or not. The UI should display different states accordingly. I am currently using SSG for page generation and SWR for user data retrieval. However, I noticed that when call ...

Exploring the transparency of material lab autocomplete drop-down text for enabling multiple selections

Check out this demo for checkboxes and tags in Material UI The code below demonstrates an autocomplete component that functions correctly. However, the drop-down text appears transparent. Is there a way to fix this issue without modifying any libraries? ...

Align the content evenly on several cards using Material-UI

Trying to work on some frontend coding, but struggling with getting the content justified properly in fixed-height MUI cards. Each card consists of a title, description, divider, and author, but I can't seem to get everything aligned correctly within ...

The integration of lodash debounce with a NextJS function is failing with the error message "[TypeError: search(...) is undefined]

I've been developing a feature in NextJS that allows users to search for YouTube videos based on their input. In order to optimize API calls, I decided to implement lodash debounce with the useCallback hook. However, I'm encountering an issue whe ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

How to Customize the Style of Material UI's Tooltip

Is there a way to customize the background color and text color of Material UI's Tooltip? I have attempted to do so using the code snippet below without success. import { createMuiTheme } from '@material-ui/core/styles'; export const theme ...

Incorporating a Material UI Icon into a FontIcon Material-UI element within a React application

I am attempting to showcase a Material-UI Icon using a React Material-UI FontIcon component. Here is my code: <FontIcon className="material-icons"/> Help </FontIcon> Instead of displaying the icon on the screen, only text is shown. Th ...

Creating a form in NextJS to securely transfer user input data to MongoDB

Being new to JavaScript, I have a basic understanding and some lack of experience, but I am eager to learn more. Recently, I embarked on a project using NextJS, an efficient framework that integrates with ReactJS. My current challenge lies in creating a si ...

Is there a way to insert and store a personalized field in the WordPress Gutenberg (block editor) dashboard?

https://i.stack.imgur.com/FZvts.png I'm currently working on my portfolio and am looking to include a gallery field. I couldn't figure out how to add a custom field in the screenshot provided. Does anyone have any insights on how this can be ach ...

Bidirectional data binding in angular 12 reactive forms

After working with angular for a while, I encountered an issue while trying to implement two-way binding. The code snippet below is where I'm facing difficulty. Since the use of [(ngModel)] has been deprecated in Angular 12 within formGroup, finding ...

What are the appropriate situations for utilizing getStaticPaths()?

Right now, an API call is being made in a main component and the fetched data is saved in a Singleton. This singleton data needs to be accessed by the getStaticPaths() function. However, due to the fact that getStaticPaths() pre-renders it, the singleton ...

Incorporating additional ES6 modules during the development process

As I build a React component, I find that it relies on an ES6 component that I'm currently developing. Since I created the latter first, what is the typical method to include it during development as I work on the second component? If the dependency w ...

What steps should you follow to launch a react-native app from Android Studio while also setting the --mode= flag?

When trying to launch my RN application from Android Studio, it runs fine with react-native run-android command. However, I need to use react-native run-android --mode=stagingdebug instead of just react-native run-android. Is there a way to accomplish thi ...

iisnode ran into a problem while handling the request. Error code: 0x6d HTTP status code: 500 HTTP subStatus code: 1013

Currently, I am working on a web application using ReactJS for the frontend and Express for the backend. My deployment platform is Azure. In order to verify that my requests are being processed correctly, I decided to conduct two API tests. The first tes ...