Denis
Denis

Reputation: 57

React. Transferring data from textarea to array JSON

I just started working with React and JSON and require some help. There is a textarea field in which a user enters some data. How to read row-wise the entered text as an array into a JSON variable of the request? Any assistance would be greatly appreciated.

The result I want is

     {
        id: 3,
        name: 'Monika',
        birthDay: '1999/01/01',
        countryDTO: 'USA',
        films: [
                  'Leon:The Professional',
                  'Star wars',
                  'Django Unchained',
               ],
    } ```

My code:

    import React from 'react';
    import { Form, FormGroup, Label } from 'reactstrap';
    import '../app.css';

    export class EditActor extends React.Component {
    state = {
        id: '',
        name: '',
        birthDay: '',
        countryDTO: '',
        films: [],
    }

    componentDidMount() {
        if (this.props.actor) {
            const { name, birthDay, countryDTO, films } = this.props.actor
            this.setState({ name, birthDay, countryDTO, films });
        }
    }

    submitNew = e => {
        alert("Actor added"),
            e.preventDefault();
        fetch('api/Actors', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: this.state.name,
                birthDay: this.state.birthDay,
                countryDTO: {
                    title: this.state.countryDTO
                },
                films: [{ title: this.state.films }]
            })
        })
            .then(() => {
                this.props.toggle();
            })
            .catch(err => console.log(err));

        this.setState({
            id: '',
            name: '',
            birthDay: '',
            countryDTO: '',
            films: ''
        });
    }

    onChange = e => {
        this.setState({ [e.target.name]: e.target.value })
    }

    render() {
        return <div>
            <table>
                    <tr>
                        <td colspan="2">   
                            <h3> <b>Add actor</b></h3>

                    <FormGroup>
                    <Label for="id">Id:  </Label>
                                <input type="text" name="id" onChange={this.onChange} value={this.state.id} /><p />

                    <Label for="name">Name:</Label>
                                <input type="text" name="name" onChange={this.onChange} value={this.state.name} /><p />

                    <Label for="birthDay">Birth day:</Label>
                    <input type="text" name="birthDay" onChange={this.onChange} value={this.state.birthDay} placeholder="1990/12/31" /><p />

                    <Label for="country">Country:</Label>
                                <input type="text" name="countryDTO" onChange={this.onChange} value={this.state.countryDTO} /><p />

                    <Label for="Films">Films:</Label>
                    <textarea name="films" value={this.state.films} onChange={this.onChange} /><p />
                    </FormGroup>

                        </td>
                    </tr>
                    <tr>
                        <td>

                <Form onSubmit={this.submitNew}>
                            <button class="editButtn">Enter</button>
                </Form>
                        </td>

                    </tr>
            </table >
        </div>;
    }
}

export default EditActor;

Upvotes: 3

Views: 1453

Answers (5)

Palash Kanti Bachar
Palash Kanti Bachar

Reputation: 616

If you change the below code it will work automatically.

State declaration

 this.state = {
      name: 'React',
      films:["Palash","Kanti"]
    };

Change in onechange function

onChange = e => {
  console.log("values: ", e.target.value)
    this.setState({ [e.target.name]: e.target.value.split(",") })
}

change in textarea

  <textarea name="films" value={this.state.films.map(r=>r).join(",")} onChange={this.onChange} />

Code is here: https://stackblitz.com/edit/react-3hrkme

Upvotes: 1

Deschant Kounou
Deschant Kounou

Reputation: 53

My understanding of your problem is that you would like to have each line in the text area dynamically added as an entry in the films array. This can be achieved as follows:

import React, { Component } from "react";

export default class textAreaRowsInState extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentTextareaValue: "",
      films: []
    };
  }

  handleChange = e => {
    const { films } = this.state;
    const text = e.target.value;
    if (e.key === "Enter") {
      // Get last line of textarea and push into films array
      const lastEl = text.split("\n").slice(-1)[0];
      films.push(lastEl);
      this.setState({ films });
    } else {
      this.setState({ currentTextareaValue: text });
    }
  };

  render() {
    const { currentTextareaValue } = this.state;
    return (
      <textarea
        defaultValue={currentTextareaValue}
        onKeyPress={this.handleChange}
      />
    );
  }
}

Keep in mind that this method is not perfect. For example, it will fail if you add a new line anywhere other than at the end of the textarea. You can view this solution in action here:

https://codesandbox.io/s/infallible-cdn-135du?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 1

mohamed ibrahim
mohamed ibrahim

Reputation: 583

You have to close textarea tag and the following code is :

<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>

Upvotes: 1

user10971804
user10971804

Reputation: 281

You can use split() :

films: {this.state.films.split(",")}

Upvotes: 0

Siddharth Rathod
Siddharth Rathod

Reputation: 638

change textarea() tag to

<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>

Upvotes: 0

Related Questions