Home > Enterprise >  React: How to prefill textboxes with Json data?
React: How to prefill textboxes with Json data?

Time:07-15

I am fetching the data from api.Api that returns json data. Data needs to be prefilled in the textbox and textarea. The api response is [{"ProdName":"Test Product","ProdDescr":"Testing"}]

How to prefill ProdName textbox with value Test Product, ProdDesc Textarea with Testing.

import React from 'react';

export class Edit_ProdInfo extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Prod_ID: '',
      ProdName: '',
      ProdDescr: '',
      ProdInfo: [],
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount() {
    this.setProdTextBoxes();
  }

  async setProdTextBoxes() {
    await fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((data) => {
        this.setState({
          Prod_ID: this.props.key_id,

          ProdInfo: data,

          loading: false,
        });

        console.log(this.state.ProdInfo);
      });
  }

  //[{"TemplateName":"CA States","TemplateDescr":""}]

  handleChange(event) {
    this.setState({ ProdName: event.target.value });
  }

  render() {
    return (
      <div>
        <form>
          <input type='text' ID='ProdName' value={this.state.ProdName} />{' '}
          <textarea
            name='ProdDescr'
            rows='4'
            cols='65'
            value={this.state.ProdDescr}
          ></textarea>
        </form>
      </div>
    );
  }
}

export default Edit_ProdInfo;

CodePudding user response:

To prefill the data, You need to call the function inside componentDidMount,

componentDidMount() {
  setProdTextBoxes()
}

Put the setState inside the componentDidMount or the function inside the componentDidMount.

You also need call the function handleChange in onChange like below,

<input type="text" ID="ProdName" onChange={(e) => handleChange(e)} value={this.state.ProdName}/> 

So that the state will get updated and the value will replicated in the text box.

CodePudding user response:

You need to change in below section. but if you use only single record and have a access of api modification then try to return single record instead of array. it will avoid indexing [0] in this scenario.

async setProdTextBoxes() {
    await fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((data) => {
      if(data && data.length>0)
        {
          this.setState({
          Prod_ID: this.props.key_id,
          ProdName:data[0].ProdName,
          ProdDescr:data[0].ProdDescr,
          ProdInfo: data,    
          loading: false,
         });
        }

        console.log(this.state.ProdInfo);
      });
  }
  • Related