Search code examples
reactjswysiwygrich-text-editor

How to turn React RichTextEditor class into a function?


I'm using react-rte in my project and try to get the text editor working, but with no success. I copied the class from the above website (code below) and tried to turn it into a function, since I have more experience with them. What am I missing?

Class from react-rte-link

class MyStatefulEditor extends Component {
  static propTypes = {
    onChange: PropTypes.func
  };

  state = {
    value: RichTextEditor.createEmptyValue()
  }

  onChange = (value) => {
    this.setState({value});
    if (this.props.onChange) {
      // Send the changes up to the parent component as an HTML string.
      // This is here to demonstrate using `.toString()` but in a real app it
      // would be better to avoid generating a string on each change.
      this.props.onChange(
        value.toString('html')
      );
    }
  };

  render () {
    return (
      <RichTextEditor
        value={this.state.value}
        onChange={this.onChange}
      />
    );
  }
}

And here's my function:

function MyStatefulEditor ({ values, setValues }) {
  const value = RichTextEditor.createEmptyValue();

  console.log(values, setValues);

  const handleChange = name => event => {
    setValues({ ...values, [name]: event.target.value });
    value.toString("html");
  };

  return (
    <RichTextEditor
      value={values.bodyText}
      onChange={handleChange("bodyText")}
      required
      id="body-text"
      name="bodyText"
      className={classes.textField}
      type="string"
      multiline
      rows="20"
      variant="filled"
      style={{ minHeight: 410 }}
    />
  );
}

Solution

  • I got it working, in case anyone is looking for the answer!

    // values.bodyText has the database information, 
    // if I'm not adding a new thing, but editing an old one
    
    <BodyTextEditor
      value={values.bodyText}
      setValue={bodyText => setValues({...values, bodyText })}
    />
    

    Function:

    // some things inside RTE are just for styling, delete the id's etc. 
    
    function BodyTextEditor({ value, setValue }) {
    
      const [editorValue, setEditorValue] =
        React.useState(RichTextEditor.createValueFromString(value, 'markdown'));
    
      const handleChange = value => {
        setEditorValue(value);
        setValue(value.toString("markdown"));
      };
    
      return (
        <RichTextEditor
          value={editorValue}
          onChange={handleChange}
          required
          id="body-text"
          name="bodyText"
          type="string"
          multiline
          variant="filled"
          style={{ minHeight: 410 }}
        />
      );
    }