RD17 / react-trumbowyg

React wrapper for lightweight WYSIWYG editor Trumbowyg
MIT License
146 stars 21 forks source link

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

Open Jimmyelvis opened 4 years ago

Jimmyelvis commented 4 years ago

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?

McTano commented 4 years ago

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.

Jimmyelvis commented 4 years ago

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

evg1n commented 4 years ago

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;