0

I have an app that reads <input type="text"> and let people comment on that word. I want to do is save this comment to a file and retrieve the data when I search the same name again.

eg. I input for "fish". App3 will render and shows where to comment, as I submit my comment a new file will create (eg. fish.txt) somewhere. And when I visit the word again, I can read my past comments.

This is my code so far

class App3 extends Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {items: [], text: ''};
  }

  render() {
    return (
      <div  className="app3">
        <h1>Comments</h1>
        <div className="commentsSection">
          <AddComment items={this.state.items} />
        </div>
        <form onSubmit={this.handleSubmit}>
          <textarea onChange={this.handleChange} value={this.state.text} />
          <button>Comment</button>
        </form>
      </div>
    );
  }

  handleChange(e) {
    this.setState({text: e.target.value});
  }

  handleSubmit(e) {
    e.preventDefault();
    var newItem = {
      text: this.state.text,
      id: Date.now()
    };
    this.setState((prevState) => ({
      items: prevState.items.concat(newItem),
      text: ''
    }));
  }
}

class AddComment extends React.Component {
  render() {
    return (
      <ul>
        {this.props.items.map(item => (
          <p key={item.id}>{item.text}</p>
        ))}
      </ul>
    );
  }
}

1
  • 1
    If you want to persist some data on client you can consider local storage. If you need permanent persistence, you need to send data to server and save it there. Commented Nov 25, 2016 at 6:30

1 Answer 1

1

Your problem is not specific to react. React runs on browser as you know, and browser knows nothing about your file system, therefore, it can't really read files on a whim - user has to upload it via file input. Which I believe does not satisfy your requirement. What you need in this case is some sort of server, and persistence. The server will have to send static files to the browser (images, html, styles, javascript files), and communicate to your application over HTTP protocol, to serve the data you need. Now the server, could get the data from files, or database or wherever.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.