I'm working on a Blog project using React and Node to create the frontend and the backend of it.
I'm trying to implement TinyMCE in my admin frontend, and it works, meaning I can see the editor in the page, I can write in it and I can save what I write in the database. BUT when I get the articles from the database and render them on the page, what I see is: <p>This is an example.</p>
I read the docs but I can't find an answer to how to render the content properly. I tried to use html-parser, but instead of showing <p>, it shows the <p> tag. I'm not sure whether I have to change the way text is saved with tinyMCE, or the way it is displayed when doing the GET request.
This is the component where the Editor is embedded:
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import Navbar from './navbar';
import authHeader from '../services/authHeader';
import { Editor } from '@tinymce/tinymce-react';
const CreatePost = () => {
const [title, setTitle] = useState('');
const [text, setText] = useState('');
const [errors, setErrors] = useState([]);
const history = useHistory();
const handleEditorChange = (content, editor) => {
setText(content);
};
const handleSubmit = async (e) => {
try {
e.preventDefault();
const post = {
title,
text,
};
const request = await fetch('http://localhost:5000/api/posts/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: authHeader(),
},
mode: 'cors',
body: JSON.stringify(post),
});
const response = await request.json();
if (request.status === 400) {
setErrors(response);
return;
} else {
console.log(response);
history.push('/');
}
} catch (error) {
console.log(error);
}
};
return (
<div>
<Navbar></Navbar>
<div className='container mt-5'>
{errors.length > 0
? errors.map((error) => (
<p className='alert alert-warning mb-0 mt-4' key={error.msg}>
{error.msg}
</p>
))
: ''}
<form onSubmit={(e) => handleSubmit(e)}>
<div className='form-group'>
<label htmlFor='title'>Title</label>
<input
className='form-control'
type='text'
name='title'
id='title'
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<Editor
initialValue={text}
init={{
height: 500,
menubar: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount',
],
toolbar:
'undo redo | formatselect | bold italic backcolor | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | removeformat | help',
}}
onEditorChange={handleEditorChange}
/>
<button className='btn btn-primary mt-3'>Create Post</button>
</form>
</div>
</div>
);
};
export default CreatePost;