BIS Tech
BIS Tech

Reputation: 19494

How to use nested object data on ReactJS?

I ADDED ANSWER IN COMMENT

I created POST using Node.js. I passed data looks like this in Postman.

{ "quantity":20, "with_tax":{ "price":200, "currency":"lkr" } }

I created <div> like this(in Movie.jsx class)

 render() {
    return (
      <div className="card" style={{ width: "25rem" }}>
        <form onSubmit={this.props.onPostData}>

with tax price div

    <div
                className="wrap-input100 validate-input bg1"
                data-validate="Please Type Running Time"
              >
                <span className="label-input100">With Tax Price</span>
                <input
                  type="number"
                  name="with_tax_price"
                  placeholder="With Tax Price"
                  className="form-control"
                  onChange={this.props.onDataChange}
                />
              </div>

with tax currency div

              <div
                className="wrap-input100 validate-input bg1"
                data-validate="Please Type Running Time"
              >
                <span className="label-input100">With Tax Currency</span>
                <input
                  type="text"
                  name="with_tax_currency"
                  placeholder="With Tax Currency"
                  className="form-control"
                  onChange={this.props.onDataChange}
                />
              </div>

in render method I called Movie class like this,(in Movies.jsk class)

class Movies extends Component {
  constructor() {
    super();

this.state

    this.state = {
      with_tax_price: "",
      with_tax_currency: "",
      quantity: ""
    };
  }

dataChange

  dataChange(ev) {
    this.setState({
      [ev.target.name]: ev.target.value
    });
  }

postData

  postData(ev) {
    ev.preventDefault();
    const with_tax_price = this.state.with_tax_price;
    const with_tax_currency = this.state.with_tax_currency;
    var with_tax;
    const quantity = this.state.quantity;

    this.setState({
      loading: true
    });

data variable

    const data = {
      with_tax: { with_tax_price, with_tax_currency },
      quantity
    };

axios POST

    axios
      .post(apiEndpoint, data)
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });
  }

render method

  render() {
    return (
      <Movie
        onPostData={this.postData.bind(this)}
        onDataChange={this.dataChange.bind(this)}
      />
    );
  }
}

Upvotes: 4

Views: 53

Answers (1)

BIS Tech
BIS Tech

Reputation: 19494

CHANGE MY CODE INTO THIS,

in postData(ev)

{ 
ev.preventDefault();
         const with_tax = {
              price: this.state.with_tax_price,
              currency: this.state.with_tax_currency
            };
        }

data variable

 const data = {
      with_tax,
      quantity
    };

Upvotes: 1

Related Questions