I use the Draft wysiwyg for my React project .
But I can only get simple text, but I can not get and save the image.
How can I save both text and image on my server using Draft wysiwyg?
component text editor:
class TextEditor extends Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
uploadedImages: [],
};
this._uploadImageCallBack = this._uploadImageCallBack.bind(this);
}
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
};
_uploadImageCallBack(file) {
let uploadedImages = this.state.uploadedImages;
const imageObject = {
file: file,
localSrc: URL.createObjectURL(file),
};
uploadedImages.push(imageObject);
this.setState({ uploadedImages: uploadedImages });
return new Promise((resolve, reject) => {
resolve({ data: { link: imageObject.localSrc } });
});
}
render() {
const { editorState } = this.state;
return (
<div style={{ height: "100%", width: "100%" }}>
<Editor
editorState={editorState}
toolbarClassName='toolbarClassName'
wrapperClassName='wrapperClassName'
editorClassName='editorClassName'
onEditorStateChange={this.onEditorStateChange}
toolbar={{
inline: { inDropdown: true },
list: { inDropdown: true },
textAlign: { inDropdown: true },
link: { inDropdown: true },
history: { inDropdown: true },
image: { uploadCallback: this._uploadImageCallBack },
inputAccept:
"application/pdf,text/plain,application/vnd.openxmlformatsofficedocument.wordprocessingml.document,application/msword,application/vnd.ms-excel",
}}
/>
</div>
);
}
}
export default TextEditor;
I use the TextEditor component, which is a class component, in another component, which is the functional component, and from there I send the data to the server.
thank for those to help me!
Related
I am working on a rich text editor used for converting plain html to editor content with next js for ssr. I got this error window is not defined so I search a solution to this github link
It used a dynamic import feature of next js.
Instead of importing the Editor directly import { Editor } from "react-draft-wysiwyg";
It uses this code to dynamically import the editor
const Editor = dynamic(
() => {
return import("react-draft-wysiwyg").then(mod => mod.Editor);
},
{ ssr: false }
);
But still I'm getting this error though I already installed this react-draft-wysiwyg module
ModuleParseError: Module parse failed: Unexpected token (19:9)
You may need an appropriate loader to handle this file type.
| import dynamic from "next/dynamic";
| var Editor = dynamic(function () {
> return import("react-draft-wysiwyg").then(function (mod) {
| return mod.Editor;
| });
And this is my whole code
import React, { Component } from "react";
import { EditorState } from "draft-js";
// import { Editor } from "react-draft-wysiwyg";
import dynamic from "next/dynamic";
const Editor = dynamic(
() => {
return import("react-draft-wysiwyg").then(mod => mod.Editor);
},
{ ssr: false }
);
class MyEditor extends Component {
constructor(props) {
super(props);
this.state = { editorState: EditorState.createEmpty() };
}
onEditorStateChange = editorState => {
this.setState({ editorState });
};
render() {
const { editorState } = this.state;
return (
<div>
<Editor
editorState={editorState}
wrapperClassName="rich-editor demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
placeholder="The message goes here..."
/>
</div>
);
}
}
export default MyEditor;
Please help me guys. Thanks.
Here is a workaround
import dynamic from 'next/dynamic'
import { EditorProps } from 'react-draft-wysiwyg'
// install #types/draft-js #types/react-draft-wysiwyg and #types/draft-js #types/react-draft-wysiwyg for types
const Editor = dynamic<EditorProps>(
() => import('react-draft-wysiwyg').then((mod) => mod.Editor),
{ ssr: false }
)
The dynamic one worked for me
import dynamic from 'next/dynamic';
const Editor = dynamic(
() => import('react-draft-wysiwyg').then((mod) => mod.Editor),
{ ssr: false }
)
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
const TextEditor = () => {
return (
<>
<div className="container my-5">
<Editor
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
/>
</div>
</>
)
}
export default TextEditor
Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload
import React, { Component } from 'react'
import { EditorState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import dynamic from 'next/dynamic';
const Editor = dynamic(
() => import('react-draft-wysiwyg').then(mod => mod.Editor),
{ ssr: false })
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
export default class ArticleEditor extends Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty()
};
}
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
this.props.handleContent(
convertToRaw(editorState.getCurrentContent()
));
};
uploadImageCallBack = async (file) => {
const imgData = await apiClient.uploadInlineImageForArticle(file);
return Promise.resolve({ data: {
link: `${process.env.NEXT_PUBLIC_API_URL}${imgData[0].formats.small.url}`
}});
}
render() {
const { editorState } = this.state;
return (
<>
<Editor
editorState={editorState}
toolbarClassName="toolbar-class"
wrapperClassName="wrapper-class"
editorClassName="editor-class"
onEditorStateChange={this.onEditorStateChange}
toolbar={{
options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded', 'emoji', 'image', 'history'],
inline: { inDropdown: true },
list: { inDropdown: true },
textAlign: { inDropdown: true },
link: { inDropdown: true },
history: { inDropdown: true },
image: {
urlEnabled: true,
uploadEnabled: true,
uploadCallback: this.uploadImageCallBack,
previewImage: true,
alt: { present: false, mandatory: false }
},
}}
/>
<textarea
disabled
value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
/>
</>
)
}
}
Try to return the Editor after React updates the DOM using useEffect hook. For instance:
const [editor, setEditor] = useState<boolean>(false)
useEffect(() => {
setEditor(true)
})
return (
<>
{editor ? (
<Editor
editorState={editorState}
wrapperClassName="rich-editor demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
placeholder="The message goes here..."
/>
) : null}
</>
)
I am pretty new to React and I am trying to build this simple web app that takes a stock tag as an input and updates the graph based on the performance of the given stock. However, I can't get my graph to update. I tried using componentDidUpdate(prevProps, prevState, snapshot), but for some reason prevProps is undefined and I don't know/understand why. I tried searching online and reading the doc file, but I still can't figure it out. Any help would be appreciated.
import Search from './Search.js'
import Graph from './Graph.js'
import Sidebar from './Sidebar.js'
import './App.css'
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [{
x: [],
close: [],
decreasing: { line: { color: '#FF0000' } },
high: [],
increasing: { line: { color: '#7CFC00' } },
line: { color: 'rgba(31,119,180,1)' },
low: [],
open: [],
type: 'candlestick',
xaxis: 'x',
yaxis: 'y'
}]
,
layout: {
width: 1500,
height: 700,
font: { color: '#fff' },
title: { text: 'Stock', xanchor: "left", x: 0 }, paper_bgcolor: '#243b55', plot_bgcolor: '#243b55', yaxis: { showgrid: true, color: '#fff' },
xaxis: {
zeroline: true, color: '#fff', showgrid: true, rangeslider: {
visible: false
}
}
},
searchfield: '',
stocktag: ' '
};
this.onSearchChange = this.onSearchChange.bind(this);
this.onSubmitSearch = this.onSubmitSearch.bind(this);
}
componentDidMount() {
document.body.style.backgroundColor = '#243b55';
this.loadGraphInfo();
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log(prevProps.stocktag);
console.log(prevState.stocktag);
if (prevProps.stocktag !== prevState.stocktag) {
//this.fetchData('SPY');
}
}
onSearchChange = (event) => {
var search = event.target.value;
this.setState({ stocktag: search });
}
onSubmitSearch = (e) => {
var search = this.state.searchfield;
this.setState({ stocktag: search });
}
fetchData(stock) {
//GET DATA
//UPDATE STATE
}
loadGraphInfo() {
if (this.state.stocktag == ' ') {
this.fetchData('SPY');
} else {
this.fetchData(this.state.stocktag);
}
}
render() {
return (
<div className="App" >
<Sidebar />
<Search searchChange={this.onSearchChange} submitChange={this.onSubmitSearch} />
<Graph data={this.state.data} layout={this.state.layout} />
</div>
);
}
}
export default App;
import React, { Component } from 'react';
import './Search.css'
const Search = ({ searchChange, submitChange }) => {
return (
<div>
<div class="SearchCompInput">
<input class="SearchBar" type="text" onChange={searchChange}/>
</div>
<div class="SearchCompButton">
<button class="SearchButton" onClick={submitChange}>Search</button>
</div>
</div>
);
}
export default Search;
The prevProps.stocktag is undefined because you didn't pass any props to App component. Try this in your index.js you will see preProps value but actually it does not make any sense.
render(<App stocktag='' />, document.getElementById('root'));
componentDidUpdate(prevProps, prevState, snapshot){
console.log(prevProps.stocktag);
console.log(prevState.stocktag);
if (prevProps.stocktag !== prevState.stocktag) {
//this.fetchData('SPY');
}
}
I am not quite sure on what you are trying to accomplish here but the first thing I notice is you setState of stocktag to this.state.searchfield which is ' ' in your onSubmitSearch function.
onSearchChange = (event) => {
var search = event.target.value;
this.setState({ stocktag: search });
}
onSubmitSearch = (e) => {
var search = this.state.searchfield;
this.setState({ stocktag: search });
}
Add I will also like to add that it is good practice to set value of input to a state value like so
import React, { Component, useState } from 'react';
import './Search.css'
const Search = ({ searchChange, submitChange }) => {
const [inputValue, setInputValue] = useState('')
const handleChange = (e) => {
setInputValue(e.target.value)
searchChange(e)
}
return (
<div>
<div class="SearchCompInput">
<input class="SearchBar" type="text" value = {inputValue} onChange={handleChange}/>
</div>
<div class="SearchCompButton">
<button class="SearchButton" onClick={submitChange}>Search</button>
</div>
</div>
);
}
export default Search;
I had this problem, and it was because there was a child class that was calling super.componentDidUpdate() WITHOUT passing in the parameters. So the child class looked something like:
componentDidUpdate() {
super.componentDidUpdate();
... <-- other stuff
}
And I had to change it to:
componentDidUpdate(prevProps, prevState) {
super.componentDidUpdate(prevProps, prevState);
... <-- other stuff
}
I am trying to disable a button on click in React JS, as its function is to add articles to an array. When as user clicks saves article, the button should disable, so they can't save again.
So far for this component my code is as follows:
import React, { Component } from 'react';
import './news-hero.css';
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
const responsive = {
superLargeDesktop: {
breakpoint: { max: 4000, min: 3000 },
items: 1,
},
desktop: {
breakpoint: { max: 3000, min: 1024 },
items: 1,
},
tablet: {
breakpoint: { max: 1024, min: 464 },
items: 1,
},
mobile: {
breakpoint: { max: 464, min: 0 },
items: 1,
},
};
class NewsHero extends Component {
_isMounted = false;
state = {
loading: false,
data: [],
headline: [],
saved: []
}
saved = headline => {
this.setState(
(prevState) => ({ saved: [...prevState.saved, headline] }),
() => {
console.log('Saved articles = ', this.state.saved);
alert('Article saved');
localStorage.setItem('saved', JSON.stringify(this.state.saved));
localStorage.getItem('saved');
});
}
constructor(props) {
super(props)
this.saved = this.saved.bind(this)
}
onError() {
this.setState({
imageUrl: "../assets/img-error.jpg"
})
}
componentDidMount() {
this._isMounted = true;
this.setState({ loading: true, saved: localStorage.getItem('saved') ? JSON.parse(localStorage.getItem('saved')) : [] })
fetch('https://newsapi.org/v2/everything?q=timbaland&domains=rollingstone.com,billboard.com&excludeDomains=townsquare.media&apiKey=xxxx')
.then(headline => headline.json())
.then(headline => this.setState({ headline: headline.articles, loading: false }, () => console.log(headline.articles)))
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
return (
<div className="hero">
<h2 className="text-left">News</h2>
{this.state.loading
? "loading..."
: <div>
<Carousel
additionalTransfrom={0}
showDots={true}
arrows={true}
autoPlaySpeed={3000}
autoPlay={false}
centerMode={false}
className="carousel-hero"
containerClass="container-with-dots"
dotListClass="dots"
draggable
focusOnSelect={false}
infinite
itemClass="carousel-top"
keyBoardControl
minimumTouchDrag={80}
renderButtonGroupOutside={false}
renderDotsOutside
responsive={responsive}>
{this.state.headline.map((post, indx) => {
return (
<div className="text-left mt-5" key={indx}>
<img className="media-img card-img-top card-img-hero" src={post.urlToImage} alt="Alt text"></img>
<div className="card-body container hero-text-body">
<h1 className="card-title hero-title text-truncate">{post.title}</h1>
<button className="btn-primary btn mt-2 mb-4" onClick={() => this.saved(post)}>Save article</button>
<p className="card-text">{post.description}</p>
Read More
</div>
</div>
)
})}
</Carousel>
</div>
}
</div>
)
}
}
export default NewsHero;
Other questions answers don't really answer this straight question as the other questions are bespoke answers to other scenario codes.
You can pass the event to your onClick() function.
onClick={(e) => this.saved(e, post)}
You can then use that event and currentTarget to get the HTML element that contains the onClick and disable that element.
saved = (e, headline) => {
// Disable clicked button
e.currentTarget.disabled = true;
...
}
As Ed Lucas suggest, you can do it like that or, you can maintain your button status on the state and change it according to click event.
import React, { Component } from 'react';
import { render } from 'react-dom';
class App extends Component {
constructor() {
super();
this.state = {
btnStatus: false
};
}
render() {
return (
<div>
<button
disabled={this.state.btnStatus}
onClick={() => this.setState({ btnStatus: true })}
>
CLICK
</button>
</div>
);
}
}
render(<App />, document.getElementById('root'));
I am using react-table to display the data. I want to keep my table column outside the react component since it is too big to put in there and reusability purpose as well. I made a table config to hold all my table config. The problem is I am using some of my local state reference in columns. So when I import column from config file it gives error where I have used this.state.
tableconfig.js
export const table = [
{
resizable: false,
width: 50,
Cell: ({ original }) => {
const { pageActivity, pageNumber } = this.state;
const currentPageActivityRow = {
...get(pageActivity[pageNumber], "selectedRows")
};
return (
<Checkbox
checked={currentPageActivityRow[original.id] === true}
onChange={() => this.selectRows(original.id)}
/>
);
}
},
{
Header: "Contact ID",
accessor: "id"
}
];
tableComponent.js
import {table} from '../config';
constructor(props){
super(props);
this.state = {
pageNumber: 1,
search: "",
error: "",
dialogOpen: false,
isFilerActive: false,
selectedFilters: {},
pageActivity: {}
};
this.columns = table
}
maybe try binding your table? It has to be a function though
const table = () => (
[
{
resizable: false,
width: 50,
Cell: ({ original }) => {
const { pageActivity, pageNumber } = this.state;
const currentPageActivityRow = {
...get(pageActivity[pageNumber], "selectedRows")
};
return (
<Checkbox
checked={currentPageActivityRow[original.id] === true}
onChange={() => this.selectRows(original.id)}
/>
);
}
},
{
Header: "Contact ID",
accessor: "id"
}
];
)
// tableComponent.js
constructor(props){
super(props);
this.state = {
pageNumber: 1,
search: "",
error: "",
dialogOpen: false,
isFilerActive: false,
selectedFilters: {},
pageActivity: {}
};
this.columns = table.bind(this);
}
I have the following Higher Order Component to create a loading on my components:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Spinner from 'components/spinner';
const WithSpinner = (WrappedComponent) => {
return class SpinnerWrapper extends Component {
componentWillReceiveProps(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
}
render (){
const { loading } = this.props;
return (
<div>
{loading ?
<Spinner />
:
<WrappedComponent {...this.props}>{this.props.children}</WrappedComponent>}
</div>)
}
}
SpinnerWrapper.propTypes = {
loading: PropTypes.bool,
};
SpinnerWrapper.defaultProps = {
loading: true,
};
return SpinnerWrapper;
};
export default WithSpinner;
and I have the following component who is wrapping in WithSpinner
const updateChartSeries = answersSummary => ({
chartSeries: TasksTransforms.fromAnswerSummaryToClickEffectivenessChart(answersSummary),
transposed: false,
viewOptions: { type: 'pie', stacked: false, column: false },
});
class ClickEffectivenessChart extends Component {
constructor(props) {
super(props);
this.state = {
chartSeries: [],
viewOptions: {
type: 'pie',
stacked: false,
column: false,
},
title: 'Click Effectiveness',
};
}
componentWillReceiveProps({ answersSummary }) {
this.setState(updateChartSeries(answersSummary));
}
handleChartType = (type = 'pie') => {
switch (type) {
case 'pie':
this.setState({ viewOptions: { type: 'pie', stacked: false, column: false } });
break;
case 'bar':
this.setState({ viewOptions: { type: 'bar', stacked: false, column: false } });
break;
case 'column':
this.setState({ viewOptions: { type: 'bar', stacked: false, column: true } });
break;
default:
break;
}
}
optionsDropdown = () => {
const options = [
{ onClick: () => this.handleChartType('pie'), text: 'Pie' },
{ onClick: () => this.handleChartType('bar'), text: 'Bar' },
{ onClick: () => this.handleChartType('column'), text: 'Column' },
];
return options;
}
render() {
const { chartSeries, viewOptions, title } = this.state;
return (
chartSeries.length > 0 &&
<div className="content" >
<h4>{title}</h4>
<div className="box">
<EffectivenessChart type={viewOptions.type} series={chartSeries} title={title} optionMenu={this.optionsDropdown()} stacked={viewOptions.stacked} column={viewOptions.column} transposed />
</div>
</div>
);
}
}
ClickEffectivenessChart.propTypes = {
answersSummary: PropTypes.object, //eslint-disable-line
};
ClickEffectivenessChart.defaultProps = {
answersSummary: {},
};
export default WithSpinner(ClickEffectivenessChart);
And sometimes the componentWillReceiveProps it no trigger and I can see why. I'm assuming that my WithSpinner controller have a problem but I can see what is the problem. The same behavior happen in all components wrapped with the WithSpinner controller
Any help please?
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Heatmap from 'components/heatmap';
import ClickEffectivenessChart from './click_effectiveness_chart';
import ClickEffectivenessTable from './click_effectiveness_table';
import AreaChart from './area_chart';
import SctHeatmap from './sct_heatmap';
class SctAnswersSummary extends Component {
componentDidMount() {
if (this.props.questionId) { this.fetchData(); }
}
componentDidUpdate(prevProps) {
if (prevProps.questionId !== this.props.questionId) { this.fetchData(); }
}
fetchData = () => {
const {
datacenterId, accountId, projectId, questionId,
} = this.props;
this.props.actions.questionFetchRequest(datacenterId, accountId, projectId, questionId);
this.props.actions.answersSummaryFetchRequest(datacenterId, accountId, projectId, questionId);
this.props.actions.answersSctClicksFetchRequest(datacenterId, accountId, projectId, questionId);
}
render() {
const { imageUrl, clicks, questionId, imageWidth, imageHeight } = this.props.answerSctClicks;
const { answersSummaryLoading, answersSctLoading, answersSummary } = this.props;
return (
<div className="content">
<div className="content" >
<SctHeatmap imageUrl={imageUrl} clicks={clicks} questionId={questionId} imageWidth={imageWidth} imageHeight={imageHeight} loading={answersSctLoading} />
<br />
<ClickEffectivenessChart answersSummary={answersSummary} loading={answersSummaryLoading} />
<br />
<AreaChart answersSummary={answersSummary} loading={answersSummaryLoading} />
<br />
<ClickEffectivenessTable answersSummary={answersSummary} loading={answersSummaryLoading} />
</div>
</div>
);
}
}
SctAnswersSummary.propTypes = {
datacenterId: PropTypes.string,
accountId: PropTypes.string,
projectId: PropTypes.string,
questionId: PropTypes.string,
questionSct: PropTypes.object, // eslint-disable-line react/forbid-prop-types
actions: PropTypes.shape({
questionSctFetchRequest: PropTypes.func,
}).isRequired,
answersSummaryLoading: PropTypes.bool,
answersSctLoading: PropTypes.bool,
};
SctAnswersSummary.defaultProps = {
datacenterId: null,
accountId: null,
projectId: null,
questionId: null,
questionSct: {},
answersSummaryLoading: true,
answersSctLoading: true,
};
export default SctAnswersSummary;
It's because your HOC is a function stateless component, meaning that it doesn't have any lifecycle events. You need to convert WithSpinner to a class component and then the lifecycle events should flow through to your wrapped component:
const WithSpinner = (WrappedComponent) => {
return class extends React.Component {
componentWillReceiveProps(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
}
render() {
return <div>
{this.props.loading ?
<Spinner />
:
<WrappedComponent {...this.props}>
{this.props.children}
</WrappedComponent>}
</div>
}
}
}