PumpkinBreath
PumpkinBreath

Reputation: 915

How can you update a textarea's value dynamically while still being able to edit it - React

I have a textarea with an onChange handler:

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

but I also want to be able to set the value attribute dynamically based on data from MongoDB. It is for a diary app so the idea is that it looks for entries by setting value={this.displayEntry()}. Trouble is, I can't type in the textarea because every time I enter a key the onChange fires and the value is preset to whatever came from MongoDB or empty string.

Function for adding code from MongoDB (journal comes from Redux)

displayEntry() {
    const { todaysDate } = this.state;
    const { journal } = this.props;
    if (journal) {
        for (let entry of journal.data.entries) {
            if (entry.date === todaysDate) {
                return entry.content;
            }
        }
        return "";
    }
    return "";
}

I hope it's clear what I want to achieve. Is there a way round this problem?

Upvotes: 0

Views: 1130

Answers (1)

Peter Ambruzs
Peter Ambruzs

Reputation: 8213

I think you must initialise the state from the redux data only once. Then you can continue to edit it.

For example (lets suppose that the name of your text area is journal):

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

getEntry() {
    const { todaysDate } = this.state;
    const { journal } = this.props;
    if (journal) {
        for (let entry of journal.data.entries) {
            if (entry.date === todaysDate) {
                return entry.content;
            }
        }
        return "";
    }
    return "";
}

componentDidMount() {
      this.setState({
        journal: getEntry()
    });
}

// in render
<textarea value={this.state.journal} onChange={this.onChange} />

Upvotes: 2

Related Questions