react-trumbowyg icon indicating copy to clipboard operation
react-trumbowyg copied to clipboard

How to get the value typed in the editor into state?

Open Jimmyelvis opened this issue 5 years ago • 3 comments

I have a simple form in my project, with three fields, two regular fields, and one react-trumbowyg field. It seems like I successfully set everything up. I'm not getting any errors in my console. However, I'm not able to get any value typed into the trumbowyg editor into my state.

Here are the relevant bits of code I'm using:

The import statements

import 'react-trumbowyg/dist/trumbowyg.min.css';
import Trumbowyg from 'react-trumbowyg';
import jquery from 'jquery';

The constructor

constructor(props) {
    super(props);
    this.state = {
      text: ""
    };

    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

The onchange event that occurs when a user types into a field

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

The react-trumbowg component

 <Trumbowyg id='react-trumbowyg'
     placeholder="text"
      name="text"
     value={this.state.text}
      onChange={this.onChange}
        error={errors.text}
    />

Using the chrome Redux tools all I see is just empty quotes after submission for the text field. Am I setting up the actual component right?

Jimmyelvis avatar Oct 05 '19 22:10 Jimmyelvis

You want data instead of value, but you're going to run into problems with the cursor jumping back to the start on input until issue #1 is fixed.

McTano avatar Oct 29 '19 19:10 McTano

I tried it with data but I'm still having the same problems

Jimmyelvis avatar Nov 04 '19 23:11 Jimmyelvis

Can you please try this? You can compose a controlled wrapper for Trumbowyg component. I normally use it with react-redux, I tried to simplify it with React Hooks.

tl;dr: Codesandbox Example

import React, {useState} from "react";
import "react-trumbowyg/dist/trumbowyg.min.css";
import Trumbowyg from "react-trumbowyg";

const TextEditor = () => {

  const [textEditorValue, setTextEditorValue] = useState("");
  
  return (
    <Trumbowyg
      data={textEditorValue}
      onChange={(event) => setTextEditorValue(event.target.innerText)}
    />
  )
}

export default TextEditor;

Then import it as you normally would:

File Tree:

/src
|
|_ /components
|  |_ TextEditor.jsx
|
|_App.jsx
import React from "react";
import TextEditor from "./components/TextEditor.jsx";

const App = () => {
  return (
    <App>
      <TextEditor/>
    </App>
  )
}

export default App;

evg1n avatar Apr 01 '20 13:04 evg1n