draft-js Cannot read property 'getIn' of undefined ( getUpdatedSelectionState ) - reactjs

I have this error with draft-js with draft-js-plugins-editor
STRANGE BEHAVIOR: it only happens, when I refocus to first line of editor after writing, when trying to set for eg. the header of first line to H1 it changes previous focused line
ERROR: Uncaught TypeError: Cannot read property 'getIn' of undefined
FULL ERROR:
Uncaught TypeError: Cannot read property 'getIn' of undefined
at getUpdatedSelectionState (getUpdatedSelectionState.js?a009439:34)
at getDraftEditorSelectionWithNodes (getDraftEditorSelectionWithNodes.js?a009439:37)
at getDraftEditorSelection (getDraftEditorSelection.js?a7f8e9b:35)
at editOnSelect (editOnSelect.js?a7f8e9b:32)
at DraftEditor.react.js?f8ee1ff:148
at HTMLUnknownElement.callCallback (react-dom.development.js?5f39724:542)
at Object.invokeGuardedCallbackDev (react-dom.development.js?5f39724:581)
at Object.invokeGuardedCallback (react-dom.development.js?5f39724:438)
at Object.invokeGuardedCallbackAndCatchFirstError (react-dom.development.js?5f39724:452)
at executeDispatch (react-dom.development.js?5f39724:836)
This is my component:
/* eslint-disable react/no-multi-comp */
import React, {Component} from 'react';
import sv from '../../config/styleVariables'
import Editor from 'draft-js-plugins-editor';
import {EditorState,convertToRaw} from 'draft-js'
import createToolbarPlugin from 'draft-js-static-toolbar-plugin';
import {
ItalicButton,
BoldButton,
UnderlineButton,
HeadlineOneButton,
HeadlineTwoButton,
HeadlineThreeButton,
UnorderedListButton,
OrderedListButton,
BlockquoteButton,
} from 'draft-js-buttons'
export default class TextArea extends Component {
constructor(props){
super(props)
this.state = {
editorState: EditorState.createEmpty(),
}
const toolbarPlugin = createToolbarPlugin({
structure: [
BoldButton,
ItalicButton,
UnderlineButton,
HeadlineOneButton, ,
HeadlineTwoButton,
HeadlineThreeButton,
UnorderedListButton,
OrderedListButton,
// BlockquoteButton,
]
})
const { Toolbar } = toolbarPlugin;
this.Toolbar = Toolbar
this.plugins = [toolbarPlugin];
}
onChange(editorState){
this.setState({
editorState,
})
this.props.update(JSON.stringify(convertToRaw(editorState.getCurrentContent())))
}
focus(){
this.editor.focus();
}
render() {
const {Toolbar, plugins} = this
const {name} = this.props
return (
<div className="TextArea">
{/*language=SCSS*/}
<style jsx global>{`
.TextArea .headlineButtonWrapper {
display: inline-block;
}
.TextArea {
background: ${sv.white};
}
.TextArea > div>div:first-child {
display: flex;
padding: 0 0 .25em 0;
border-bottom: 1px solid ${sv.border};
}
.TextArea > div>div:first-child>div button{
background: transparent;
cursor: pointer;
border: none;
display: flex;
align-items: center;
justify-content: center;
width: 3em;
height: 2.5em;
font-size: .8em;
margin-right: .2em;
}
.TextArea > div>div:first-child>div button:hover {
background: ${sv.extraLight};
color: ${sv.primary};
}
.TextArea .DraftEditor-root {
padding: 0 .5em;
cursor: text;
}
.TextArea .headlineButton {
background: #fbfbfb;
color: #888;
font-size: 18px;
border: 0;
padding-top: 5px;
vertical-align: bottom;
height: 34px;
width: 36px;
}
.TextArea .headlineButton:hover,
.TextArea .headlineButton:focus {
background: #f3f3f3;
}
`}
</style>
<div onClick={this.focus.bind(this)}>
<Toolbar key={name} />
<Editor
editorState={this.state.editorState}
onChange={this.onChange.bind(this)}
plugins={plugins}
ref={(element) => {
this.editor = element
}}
/>
</div>
</div>
);
}
}
My component looks like this:

I meet the same problem. It looks like because call editorState.getBlockTree(anchorBlockKey).getIn(...) in getUpdatedSelectionState.js the editorState.getBlockTree(anchorBlockKey) is undefined whenever the block type is unstyled.
I have no idea how to fix it, so make a work around solution like this:
const headerOne = '<h1>Title</h1>';
const blocksFromHTML = convertFromHTML(headerOne);
const state = ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap
);
this.state = {
editorState: EditorState.createWithContent(state)
}
But there will be another problem when you press enter new line will be H1 either.

Related

Implementing animation when removing Toast

I have a working ToastList that enables me to click a button multiple times and generate a toast each time. On entry, I have an animation, but when I remove the toast, I do not get an animation. I am using Typescript and functional components.
My component is as follows:
import React, { useCallback, useEffect, useState } from 'react';
import * as Styled from './Toast.styled';
export interface ToastItem {
id: number;
title: string;
description: string;
backgroundColor: string;
}
export interface ToastProps {
toastList: ToastItem[];
setList: React.Dispatch<React.SetStateAction<ToastItem[]>>;
}
export default function Toast(props: ToastProps) {
const deleteToast = useCallback(
(id: number) => {
const toastListItem = props.toastList.filter((e) => e.id !== id);
props.setList(toastListItem);
},
[props.toastList, props.setList]
);
useEffect(() => {
const interval = setInterval(() => {
if (props.toastList.length) {
deleteToast(props.toastList[0].id);
}
}, 2000);
return () => {
clearInterval(interval);
};
}, [props.toastList, deleteToast]);
return (
<Styled.BottomRight>
{props.toastList.map((toast, i) => (
<Styled.Notification
key={i}
style={{ backgroundColor: toast.backgroundColor }}
>
<button onClick={() => deleteToast(toast.id)}>X</button>
<div>
<Styled.Title>{toast.title}</Styled.Title>
<Styled.Description>{toast.description}</Styled.Description>
</div>
</Styled.Notification>
))}
</Styled.BottomRight>
);
}
And my styling is done using styled-components and is as follows:
import styled, { keyframes } from 'styled-components';
export const Container = styled.div`
font-size: 14px;
position: fixed;
z-index: 10;
& button {
float: right;
background: none;
border: none;
color: #fff;
opacity: 0.8;
cursor: pointer;
}
`;
const toastEnter = keyframes`
from {
transform: translateX(100%);
}
to {
transform: translateX(0%);
}
}
`;
export const BottomRight = styled(Container)`
bottom: 2rem;
right: 1rem;
`;
export const Notification = styled.div`
width: 365px;
color: #fff;
padding: 15px 15px 10px 10px;
margin-bottom: 1rem;
border-radius: 4px;
box-shadow: 0 0 10px #999;
opacity: 0.9;
transition .1s ease;
animation: ${toastEnter} 0.5s;
&:hover {
box-shadow: 0 0 12px #fff;
opacity: 1;
}
`;
export const Title = styled.p`
font-weight: 700;
font-size: 16px;
text-align: left;
margin-bottom: 6px;
`;
export const Description = styled.p`
text-align: left;
`;
When I click a button, I just add an element to the state list, like:
toastProps = {
id: list.length + 1,
title: 'Success',
description: 'Sentence copied to clipboard!',
backgroundColor: '#5cb85c',
};
setList([...list, toastProps]);
My component is rendered like:
<Toast toastList={list} setList={setList}></Toast>
I would like to add animation when a toast exits, but do not know how. I have tried changing the style according to an additional prop I would send to the styled components, but this way all the toasts animate at the same time. My intuition is that I should use useRef(), but I am not sure how. Thanks in advance for any help you can provide.

Closing modal window by clicking on backdrop (ReactJS)

Could you please help me with one issue? I'd like to make a closing modal window by clicking on backdrop (using ReactJS). But in result window is closing even i click on modal window (at any position).
Here is my code:
import React from "react";
import { Fragment } from "react";
import ReactDOM from "react-dom";
import "./_Modal.scss";
const Backdrop = (props) => {
return (
<div className="backdrop" onClick={props.onClose}>
{props.children}
</div>
);
};
const ModalOverlay = (props) => {
return <div className="modal">{props.children}</div>;
};
const portalItem = document.getElementById("overlays");
const Modal = (props) => {
return (
<Fragment>
{ReactDOM.createPortal(
<Backdrop onClose={props.onClose}>
<ModalOverlay>{props.children}</ModalOverlay>
</Backdrop>,
portalItem
)}
</Fragment>
);
};
export default Modal;
And here is CSS:
.backdrop {
position: fixed;
top:0;
left: 0;
width: 100%;
height: 100vh;
z-index: 20;
background-color: rgba(0,0,0, 0.7);
display: flex;
justify-content: center;
align-items: flex-start;
overflow: auto;
padding-bottom: 15vh;
}
.modal {
position: relative;
max-width: 70%;
top: 5vh;
background-color: $darkgrey;
padding: 1rem;
border-radius: 1.5rem;
box-shadow: 0 1rem 1rem rgba(0,0,0, 0.25);
z-index: 30;
}
}
I'm just start to learning frontend, therefore do not judge strictly )
Just for understanding other people: after adding event.stopPropagation() in ModalOverlay everything works!
const ModalOverlay = (props) => {
return (
<div
className="modal"
onClick={(event) => {
event.stopPropagation();
}}
>
{props.children}
</div>
);
};

React Context API returns undefined

I'm quite new to React, and i'm trying to make a ToDoList. I have a Modal with a submit button that when pressed should add a ToDoItem. But since i didn't want to prop drill my way through this i wanted to use the Context API. The Context API confuses me quite a bit, maybe i'm just a moron, but i have a hard time understanding why i have to make a hook and pass that as the value in the provider. I thought that in the ToDoContext that i already defined the default value as a empty array, so i just did it again.
In the console at line 62, which is my initial render it says that it's undefined, after the pressing the Add ToDo I get the same message.
App.jsx
import React, { useState } from "react";
import { render } from "react-dom";
import { ThemeProvider } from "emotion-theming";
import { defaultTheme } from "./theme";
import { Global, css } from "#emotion/core";
import Header from "./components/Header";
import ToDoList from "./components/ToDoList";
import AddBtn from "./components/AddBtn";
import ToDoContext from "./ToDoContext";
const App = () => {
const [toDoItems] = useState([]);
return (
<>
{/*Global styling*/}
<Global
styles={css`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
text-decoration: none;
}
`}
/>
{/*App render start from here*/}
<ThemeProvider theme={defaultTheme}>
<ToDoContext.Provider value={toDoItems}>
<Header />
<main>
<ToDoList />
<AddBtn />
</main>
</ToDoContext.Provider>
</ThemeProvider>
</>
);
};
render(<App />, document.getElementById("root"));
ToDoContext.jsx
import { createContext } from "react";
const ToDoContext = createContext([[], () => {}]);
export default ToDoContext;
AddBtn.jsx
import React, { useState, useContext } from "react";
import { css } from "emotion";
import Modal from "../Modal";
import ToDoContext from "../ToDoContext";
const BtnStyle = css`
position: fixed;
bottom: 0;
right: 0;
cursor: pointer;
display: block;
font-size: 7rem;
`;
const ModalDiv = css`
position: fixed;
left: 50%;
background-color: #e6e6e6;
width: 60%;
padding: 20px 20px 100px 20px;
display: flex;
flex-direction: column;
align-items: center;
max-width: 400px;
height: 50%;
transform: translate(-50%, -50%);
border-radius: 20px;
top: 50%;
`;
const textareaStyle = css`
resize: none;
width: 100%;
height: 200px;
font-size: 1.25rem;
padding: 5px 10px;
`;
const timeStyle = css`
font-size: 3rem;
display: block;
`;
const modalSubmit = css`
width: 100%;
font-size: 3rem;
cursor: pointer;
margin-top: auto;
`;
const Label = css`
font-size: 2rem;
text-align: center;
display: inline-block;
margin-bottom: 50px;
`;
const AddBtn = () => {
const [showModal, setShowModal] = useState(true);
const [time, setTime] = useState("01:00");
const [toDoItems, setToDoItems] = useContext(ToDoContext);
console.log(toDoItems);
return (
<>
<div className={BtnStyle} onClick={() => setShowModal(!showModal)}>
<ion-icon name="add-circle-outline"></ion-icon>
</div>
{showModal ? (
<Modal>
<div className={ModalDiv}>
<div>
<label className={Label} htmlFor="time">
Time
<input
className={timeStyle}
type="time"
name="time"
value={time}
onChange={(e) => setTime(e.target.value)}
/>
</label>
</div>
<label className={Label} htmlFor="desc">
Description
<textarea
className={textareaStyle}
name="desc"
placeholder={`Notify yourself this message in ${time}`}
></textarea>
</label>
<button
className={modalSubmit}
onClick={() => {
setToDoItems(
toDoItems.push({
time,
})
);
}}
>
Add ToDo
</button>
</div>
</Modal>
) : null}
</>
);
};
export default AddBtn;
There are few issues in your code to fix:
useState returns a value and a setter. With this line of code, const [toDoItems] = useState([]);, you are just passing an empty array to your context.
So do this:
const toDoItems = useState([]);
In your ToDoContext.js, just pass an empty array as argument (initial value)
const ToDoContext = createContext([]);
Working copy of your code is here. (see console logs)
Also, I noticed that you are pushing the todo in setTodoItems in AddBtn.js.
Don't do this:
onClick={() => {
setToDoItems(
toDoItems.push({
time
})
);
}}
Do this:
onClick={() => {
setToDoItems(
toDoItems.concat([
{
time
}
])
);
}}

How can I change the styles of the react-toastify popup message?

I want to add my own custom style to the react-toastify message popup, depending on whether its success or error. So far I tried the following approach:
toastify.js
import { toast, Slide } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { css } from "glamor";
toast.configure({
position: toast.POSITION.BOTTOM_RIGHT,
autoClose: 3000,
transition: Slide,
pauseOnFocusLoss: false,
className: css({
backgroundColor: 'red',
}),
bodyClassName: css({
backgroundColor: 'blue',
height: '100%',
width: '100%',
})
});
export default function (message, type, styles = {}) {
switch (type) {
case type === 'success':
toast.success(message);
break;
case type === 'error':
toast.error(message);
break;
case type === 'info':
toast.info(message);
break;
case type === 'warn':
toast.warn(message);
break;
default:
toast(message);
break;
}
}
This is a function in which I define what type of message style toastify shows based on the type param. Then I call this function like this:
export default function ({params}) {
...
async function deleteTodo (id) {
try {
const res = await axios.delete(http://localhost:8000/api/delete-task/${id});
toastifyMessage(res.data, 'success');
} catch (error) {
errorInfo(toastifyMessage(error, 'error'));
}
}
return (
<li className="menu-item">
<i
className="fas fa-trash"
onClick={() => deleteTask(task._id)}
></i>
</li>
);
}
And this is what I get:
I still get that white background. All I want is to remove the default styles and add my own for success and error.
for custom style react-toastify
css
.Toastify__toast--error {
border: 1px solid #EB5757;
border-radius: 50px !important;
background: #FAE1E2 !important;
}
.Toastify__toast--error::after {
content : url('../assets/images/svg/closeToast.svg'); // Your svg Path
position: absolute;
color: #333333;
font-size: 15px;
font-weight: 700;
left:265px;
padding-top: 14px !important;
}
.Toastify__toast--error::before {
content: url("../assets/images/svg/errorToast.svg");// Your svg Path
position:relative;
z-index:100000;
left:12px;
top:6px;
}
.Toastify__toast--success {
border: 1px solid #3A9EA5 !important;
border-radius: 50px !important;
background: #F0F9FA !important;
}
.Toastify__toast--success::before {
content: url("../assets/images/svg/successToast.svg");// Your svg Path
position:relative;
z-index:100000;
left:12px;
top:6px;
}
.Toastify__toast--success::after {
content : url('../assets/images/svg/closeToast.svg');// Your svg Path
position: absolute;
color: #333333;
font-size: 15px;
font-weight: 700;
left:265px;
padding-top: 14px !important;
}
.Toastify__toast--warning {
border: 1px solid #E78326 !important;
border-radius: 50px !important;
background: #FADFC5 !important;
}
.Toastify__toast--warning::before {
content: url("../assets/images/svg/warnToast.svg");// Your svg Path
position:relative;
z-index:100000;
left:12px;
top:6px;
}
.Toastify__toast--warning::after {
content : url('../assets/images/svg/closeToast.svg'); // Your svg Path
position: absolute;
color: #E78326;
font-size: 15px;
font-weight: 700;
left:265px;
padding-top: 14px !important;
}
.Toastify__toast-body {
color: #444C63 ;
font-size: 16px;
padding-left: 20px;
line-height: 20px;
padding: 0px;
padding-top: 25px;
width: 100%;
font-weight: 400;
margin-left: 25px !important;
}
.Toastify__toast > button> svg {
display: none;
}
In my case (also a React app) I only needed to change:
background color of warning and error
progress bar color
font
I found this to be the easiest & quickest solution. In my app's CSS file I overwrite the background-property in the default classes. I also define my own classes for toast body and the progress bar:
/* https://fkhadra.github.io/react-toastify/how-to-style/ */
.Toastify__toast--warning {
background: #FFE8BC !important;
}
.Toastify__toast--error {
background: #FCA7A9 !important;
}
.toastBody {
font-family: "Atlas Grotesk Web", Arial, Helvetica, sans-serif;
color: #10171D; /* #10171D */
font-size: 0.875rem !important;
}
.toastProgress {
background: #333F48 !important;
}
To use my classes:
<ToastContainer
progressClassName="toastProgress"
bodyClassName="toastBody"
/>
Easest way to define a custom method, which can take the type of notification, content, and toast options. With the type of notification, you can pass different classNames to your custom content and override root toast component styles. Typescript example:
export enum NOTIFICATIONS_TYPES {
SUCCESS = 'success',
ERROR = 'error',
}
const NotificationStringContent: React.FunctionComponent<{
content: string;
}> = ({ content }) => (
<Typography component="p" variant="text-200">
{content}
</Typography>
);
export const showNotification = (
type: NOTIFICATIONS_TYPES,
content: string | React.ReactElement,
options: ToastOptions = {}
) => {
const toastContent = typeof content === 'string' ? (
<NotificationStringContent content={content} />
) : (
content
);
toast(toastContent, {
className: classnames(styles.toast, {
[styles.toastSuccess]: type === NOTIFICATIONS_TYPES.SUCCESS,
[styles.toastError]: type === NOTIFICATIONS_TYPES.ERROR,
}),
...options,
});
};
const NotificationContainer: React.FunctionComponent<{}> = () => (
<ToastContainer
position="bottom-left"
hideProgressBar
closeButton={<NotificationCloseButton />}
closeOnClick={false}
pauseOnHover
/>
);
export default NotificationContainer;
import { toast } from "react-toastify";
// promise is a function that returns a promise
export const withToast = (promise) => {
toast.promise(
promise,
{
pending: {
render() {
return (
<div className="p-6 py-2 bg-green-400">
<p className="mb-2">Your transaction is being processed.</p>
<p>Hang tight... Just few more moments.</p>
</div>
);
},
icon: false,
},
success: {
render({ data }) {
return (
<div>
<p className="font-bold">
Tx: {data.transactionHash.slice(0, 20)}...
</p>
<p>Has been succesfuly processed.</p>
</div>
);
},
// other options
icon: "🟢",
},
error: {
render({ data }) {
// When the promise reject, data will contains the error
return <div>{data.message ?? "Transaction has failed"}</div>;
},
},
},
// configuration
{
closeButton: true,
}
);
};
When you need to use it:
withToast(_purchase({ Id, value }));
Depending on _purchase, your app will show different messages with different styles

Refs not working

I am trying to do something similar to this. However, I would like for the input field to stay in focus until the user clicks anywhere but within the menu or any of the submenus. I am trying to use refs following the React documentation (trying to duplicate it in fact) but I cannot get it to work.
Error
"Uncaught TypeError: _this.textInput.current.focus is not a function"
Code (input field component)
import React from 'react';
import styled from 'styled-components';
export default class TextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
focusTextInput = () => {
this.textInput.current.focus();
}
render = () => {
return (
<div>
<TextInputField
font={this.props.font}
fontSize={this.props.fontSize}
placeholder={"What?"}
type="text"
value={this.props.title}
titleLength={this.props.titleLength}
onChange={this.props.change}
onFocus={this.props.focus}
onBlur={this.props.blur}
id="titleInput"
textColor={this.props.textColor}
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
const TextInputField = styled.input`
width: 90%;
height: ${props => props.fontSize * 1.25}vw;
line-height: ${props => props.fontSize * 1.25}vw;
text-align: center;
position: absolute;
bottom: -12.5vw;
left: 5%;
margin: 0 auto;
background-color: transparent;
border: transparent;
text-overflow: ellipsis;
color: ${props => props.textColor};
font-size: ${props => props.fontSize}vw;
font-family: ${props => props.font};
&:hover {
background-color: rgba(0, 0, 0, 0.2);
}
&:focus {
outline: none;
background-color: rgba(0, 0, 0, 0.5);
}
`;
you need to attach a innerRef on your styled component, something like this.
const StyledInput = styled.input`
some: styles;
`;
<StyledInput innerRef={comp => this.input = comp} />
// this.input.focus() works 🎉

Resources