Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save my input values to text file with ReactJS?

I have contact form with three inputs fields and I want to save input values into text file when users click on the button. How can I do that.. ? Can I take example ?

My code:

import React, { } from 'react';
import logo from './logo.svg';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Container, Row, Col } from 'reactstrap';
import MapContainer from "./Map";
import { Button, ButtonGroup } from '@material-ui/core';
import axios from 'axios';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      name: '',
      phone: '',
      message: ''
    };
  }

  TextFile = () => {
    const element = document.createElement("a");
    const file = new Blob([document.getElementById('message').value], {type: 'text/plain'});
    element.href = URL.createObjectURL(file);
    element.download = "myFile.txt";
    document.body.appendChild(element); // Required for this to work in FireFox
    element.click();
  }

  handleSubmit(e){
    e.preventDefault();
    axios({
      method: "POST", 
      url:"http://localhost:3000", 
      data:  this.state
    }).then((response)=>{
      if (response.data.status === 'success'){
        alert("Message Sent."); 
        this.resetForm()
      }else if(response.data.status === 'fail'){
        alert("Message failed to send.")
      }
    })
  }

  resetForm(){

     this.setState({name: '', phone: '', message: ''})
  }

  render() {

    return (
      <div className="App">
        <header className="App-header">

          <span className="Logo">ХAРДУЕРЕН И СОФТУЕРЕН СЕРВИЗ</span>
          <br />
          <p><img src={logo} className="App-logo" alt="logo" /><span className="LogoBlink">PIZHINGSTONE</span><img src={logo} className="App-logo" alt="logo" /></p>

          <Container>
            <Row>
              <Col>

                    <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button  className="button">софтуерни инсталации</Button>
                    </ButtonGroup>

                  <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button className="button">хардуерна поддръжка</Button>
                    </ButtonGroup>

                  <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button className="button">отдалечен достъп</Button>
                    </ButtonGroup>

                  <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button className="button">ремонт по домовете</Button>
                    </ButtonGroup>

                  <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button className="button">уеб графичен интерфейс</Button>
                    </ButtonGroup>

                  <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button className="button">уеб базирани приложения</Button>
                    </ButtonGroup>

                  <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button className="button">десктоп приложения</Button>
                    </ButtonGroup>

                  <ButtonGroup color="secondary" aria-label="outlined primary button group">
                      <Button className="button">видеонаблюдение 24/7</Button>
                    </ButtonGroup>

              </Col>
            </Row>
          </Container>
        </header>


        <body className="App-Body">
          <Container>
            <Row>
              <Col>
                <ul class="list-group2">
                  <li class="list-group-item2">ИНСТАЛИРАНЕ НА ВСИЧКИ ВИДОВЕ ОПЕРАЦИОННИ СИСТЕМИ LINUX, WINDOWS VISTA/XP/7/8/10, MAC OS, СПОРЕД СИСТЕМНИТЕ ИЗИСКВАНИЯ НА ХАРДУЕРА.</li>
                  <br />
                  <li class="list-group-item2"> АБОНАМЕНТНА ХАРДУЕРНА И СОФТУЕРНА ПОДДРЪЖКА НА ВАШИЯТ ОФИС ИЛИ КОРПОРАЦИЯ.</li>
                  <br />
                  <li class="list-group-item2">ОТДАЛЕЧЕН ДОСТЪП ЗА РЕШАВАНЕ НА СОФТУЕРНИ ПРОБЛЕМИ.</li>
                  <br />
                  <li class="list-group-item2">ВЗЕМАНЕ НА ВАШИЯТ КОМПЮТЪР/ЛАПТОП ОТ АДРЕС И ДОСТАВЯНЕ ДО АДРЕСА СЛЕД РЕМОНТА.</li>
                  <br />
                  <li class="list-group-item2">ПРОЕКТИРАНЕ НА УЕБ ГРАФИЧЕН ИНТЕРФЕЙС ЗА ВАШИЯТ БИЗНЕС.</li>
                  <br />
                  <li class="list-group-item2">СЪЗДАВАНЕ НА УЕБ И ДЕСКТОП ПРИЛОЖЕНИЯ СПРЯМО НУЖДИТЕ НА ПОТРЕБИТЕЛЯ.</li>
                  <br />
                  <li class="list-group-item2">ИНСТАЛИРАНЕ НА КАМЕРИ ЗА ВИДЕОНАБЛЮДЕНИЕ С ДОСТЪП ДО КАМЕРИТЕ ЧРЕЗ МОБИЛНИ УСТРОЙСТВА.</li>
                </ul>
              </Col>
            </Row>
          </Container>
          <Container>
            <Row>
              <Col>
                <div className="App">
                  <form id="contact-form" onSubmit={this.handleSubmit.bind(this)} method="POST">
                    <div className="form-group">
                      <label htmlFor="name">Name</label>
                      <input type="text" className="form-control" id="name" value={this.state.name} onChange={this.onNameChange.bind(this)} />
                    </div>
                    <div className="form-group">
                      <label htmlFor="phone">Phone</label>
                      <input type="number" className="form-control" id="phone" aria-describedby="emailHelp" value={this.state.phone} onChange={this.onPhoneChange.bind(this)} />
                    </div>
                    <div className="form-group">
                      <label htmlFor="message">Message</label>
                      <textarea className="form-control" rows="5" id="message" value={this.state.message} onChange={this.onMessageChange.bind(this)} />
                    </div>
                    <button type="submit" className="btn btn-primary">Submit</button>
                  </form>
                </div>
            </Col>
            </Row>
            </Container>
          <Container>
                <Row>
                  <Col>
                <MapContainer></MapContainer>
                </Col>
                </Row>
          </Container>
        </body>
      </div>
    );
  }
  onNameChange(event) {
    this.setState({name: event.target.value})
    }

    onPhoneChange(event) {
    this.setState({phone: event.target.value})
    }

    onMessageChange(event) {
    this.setState({message: event.target.value})
    }
  }


export default App;

I want to create a text file if not exists with .txt extension and every time when I have new inputs fields to be at the new line :(..

like image 558
Ben Johnson Avatar asked Dec 18 '22 13:12

Ben Johnson


1 Answers

The below snippet should give you an idea.

You might have to add a polyfill for createObjectURL depending on the targeted browsers.

  TextFile = () => {
    const element = document.createElement("a");
    const file = new Blob([document.getElementById('myInput').value], {type: 'text/plain'});
    element.href = URL.createObjectURL(file);
    element.download = "myFile.txt";
    document.body.appendChild(element); // Required for this to work in FireFox
    element.click();
  }

EDIT - You dont need individual functions for each input you can combine them into one and remove onNameChange onPhoneChange etc

  onChange(event) {
    this.setState({[event.target.id]: event.target.value})}
  }

place the onChange function before the render() function..

If this doesn't work please provide a reproducible link of your issue on codepen/jsfiddle etc;.

like image 59
gandharv garg Avatar answered Dec 31 '22 02:12

gandharv garg