I want to get the content of my editor and eventually store to it to a const content. I'm getting an error of _draftJs.EditorState.getCurrentContent is not a function.
import React from 'react'
import ReactDOM from 'react-dom'
import {Editor, EditorState, RichUtils} from 'draft-js'
const content = EditorState.getCurrentContent()
console.log('str= ', EditorState.getCurrentContent())
console.log('content=', content)
class MyEditor extends React.Component {
constructor (props) {
super(props)
this.state = {editorState: EditorState.createEmpty()}
this.onChange = (editorState) => this.setState({editorState})
this.handleKeyCommand = this.handleKeyCommand.bind(this)
}
_onBoldClick () {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, 'BOLD'))
}
_onUnderlineClick () {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, 'UNDERLINE'))
}
render () {
return (
<div id='content'>
<h1>Notejs</h1>
<div id='editor'>
<button onClick={this._onBoldClick.bind(this)}>Bold</button>
<button onClick={this._onUnderlineClick.bind(this)}>Underline</button>
<Editor editorState={this.state.editorState} onChange={this.onChange} />
</div>
</div>
)
}
}
ReactDOM.render(
<MyEditor />,
document.getElementById('app')
)
this.state.editorState.getCurrentContent() not EditorState.getCurrentContent()
import convertToRaw
convertToRaw(this.state.editorState.getCurrentContent())
Lets assume that we have a save button for saving data. Additionally we needs to import convertFromRaw and convertToRaw modules which are provided by draft-js.
import React from 'react'
import ReactDOM from 'react-dom'
import { Editor, EditorState, RichUtils, ContentState, convertFromRaw, convertToRaw} from 'draft-js';
class MyEditor extends React.Component {
constructor (props) {
super(props)
this.state = {editorState: EditorState.createEmpty()}
this.onChange = (editorState) => this.setState({editorState})
this.handleKeyCommand = this.handleKeyCommand.bind(this)
}
_onBoldClick () {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState,'BOLD'))
}
_onUnderlineClick () {
this.onChange(RichUtils.toggleInlineStyle(this.state.editorState,'UNDERLINE'))
}
_onSave() {
const contentState = this.state.editorState.getCurrentContent();
const editorContentRaw = convertToRaw(contentState);
/* we can save this editorContentRaw inside the DB. */
}
render () {
return (
<div id='content'>
<h1>Notejs</h1>
<div id='editor'>
<button onClick={this._onBoldClick.bind(this)}>Bold</button>
<button onClick={this._onUnderlineClick.bind(this)}>Underline</button>
<Editor editorState={this.state.editorState} onChange={this.onChange} />
<button onClick={this._onSave.bind(this)}>Save</button>
</div>
</div>
)
}
}
ReactDOM.render(
<MyEditor />,
document.getElementById('app')
)
Related
index.js is as follows:
import './index.css';
import { render } from "react-dom";
const { React } = require('react');
const { App } = require('./App');
const { serviceWorker } = require('./serviceWorker');
ReactDOM.render( < App / > , document.getElementById('root'));
serviceWorker.unregister();
and app.jsx is as follows:
import React from "react";
import"./App.scss";
import { Login, Register } from "./components/login/index";
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoginActive : true
};
}
componentDidMount() {
this.rightSide.classList.add("right");
}
changeState() {
const { isLoginActive } = this.state;
if (isLoginActive) {
this.rightSide.classList.remove("right");
this.rightSide.classList.add("left");
}else{
this.rightSide.classList.remove("left");
this.rightSide.classList.add("right");
}
this.setState(prevState => ({
isLoginActive: !prevState.isLoginActive
}));
}
render() {
const { isLoginActive } = this.state;
const current = isLoginActive ? "Register" : "Login";
const currentActive = isLoginActive ? "Login" : "Register";
return (
<div className="App">
<div className = "login">
<div className = "container" ref={ref => (this.container = ref)}>
{isLoginActive && (
<Login containerRef={ref => (this.current = ref)} />
)}
{!isLoginActive && (
<Register containerRef={ref => {this.current = ref}} />
)}
</div>
<RightSide
current={current}
currentActive={currentActive}
containerRef={ref => (this.rightSide = ref)}
onClick={this.changeState.bind(this)}
/>
</div>
</div>
);
}
}
const RightSide = props => {
return (
<div
className = "right-side"
ref={props.containerRef}
onClick={props.onClick}
>
<div className="inner-container">
<div className="text">{props.current}</div>
</div>
</div>
);
};
export default App;
on "npm start" I get the following error:
Failed to Compile
src\index.js
Line 14:1: 'ReactDOM' is not defined no-undef
Search for the keywords to learn more about each error.
my React and ReactDOM are up to date and compatible.
I am unable to figure out the solution to this issue.
Any kind of assistance would be appreciated.
Thanks!!
You have to correct the import statement of react-dom like below.
import ReactDOM from "react-dom";
you have to import it:
https://reactjs.org/docs/react-dom.html
import ReactDOM from 'react-dom'
Check for typo.
I got the same error, it was because of the difference between ReactDom and ReactDOM.
import ReactDom from 'react-dom';
ReactDOM.render
I am working on a site that has a piece a global state stored in a file using zustand. I need to be able to set that state in a class component. I am able to set the state in a functional component using hooks but I'm wondering if there is a way to use zustand with class components.
I've created a sandbox for this issue if that's helpful:
https://codesandbox.io/s/crazy-darkness-0ttzd
here I'm setting state in a functional component:
function MyFunction() {
const { setPink } = useStore();
return (
<div>
<button onClick={setPink}>Set State Function</button>
</div>
);
}
my state is stored here:
export const useStore = create((set) => ({
isPink: false,
setPink: () => set((state) => ({ isPink: !state.isPink }))
}));
how can I set state here in a class componet?:
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<button
onClick={
{
/* setPink */
}
}
>
Set State Class
</button>
</div>
);
}
}
A class component's closest analog to a hook is the higher order component (HOC) pattern. Let's translate the hook useStore into the HOC withStore.
const withStore = BaseComponent => props => {
const store = useStore();
return <BaseComponent {...props} store={store} />;
};
We can access the store as a prop in any class component wrapped in withStore.
class BaseMyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { setPink } = this.props.store;
return (
<div>
<button onClick={setPink}>
Set State Class
</button>
</div>
);
}
}
const MyClass = withStore(BaseMyClass);
Seems that it uses hooks, so in class you can work with the instance:
import { useStore } from "./store";
class MyClass extends Component {
render() {
return (
<div>
<button
onClick={() => {
useStore.setState({ isPink: true });
}}
>
Set State Class
</button>
</div>
);
}
}
Create a React Context provider that both functional and class-based components can consume. Move the useStore hook/state to the context Provider.
store.js
import { createContext } from "react";
import create from "zustand";
export const ZustandContext = createContext({
isPink: false,
setPink: () => {}
});
export const useStore = create((set) => ({
isPink: false,
setPink: () => set((state) => ({ isPink: !state.isPink }))
}));
export const ZustandProvider = ({ children }) => {
const { isPink, setPink } = useStore();
return (
<ZustandContext.Provider
value={{
isPink,
setPink
}}
>
{children}
</ZustandContext.Provider>
);
};
index.js
Wrap your application with the ZustandProvider component.
...
import { ZustandProvider } from "./store";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<ZustandProvider>
<App />
</ZustandProvider>
</StrictMode>,
rootElement
);
Consume the ZustandContext context in both components
MyFunction.js
import React, { useContext } from "react";
import { ZustandContext } from './store';
function MyFunction() {
const { setPink } = useContext(ZustandContext);
return (
<div>
<button onClick={setPink}>Set State Function</button>
</div>
);
}
MyClass.js
import React, { Component } from "react";
import { ZustandContext } from './store';
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<button
onClick={this.context.setPink}
>
Set State Class
</button>
</div>
);
}
}
MyClass.contextType = ZustandContext;
Swap in the new ZustandContext in App instead of using the useStore hook directly.
import { useContext} from 'react';
import "./styles.css";
import MyClass from "./MyClass";
import MyFunction from "./MyFunction";
import { ZustandContext } from './store';
export default function App() {
const { isPink } = useContext(ZustandContext);
return (
<div
className="App"
style={{
backgroundColor: isPink ? "pink" : "teal"
}}
>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<MyClass />
<MyFunction />
</div>
);
}
If you aren't able to set any specific context on the MyClass component you can use the ZustandContext.Consumer to provide the setPink callback as a prop.
<ZustandContext.Consumer>
{({ setPink }) => <MyClass setPink={setPink} />}
</ZustandContext.Consumer>
MyClass
<button onClick={this.props.setPink}>Set State Class</button>
This worked out pretty well for me.
:
import React, { Component } from "react";
import { useStore } from "./store";
class MyClass extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<button
onClick={
useStore.getState().setPink() // <-- Changed code
}
>
Set State Class
</button>
</div>
);
}
}
export default MyClass;
I like to create a high order component similar to redux connect:
function connectZustand(useStore, selector) {
return (Component) =>
React.forwardRef((props, ref) => <Component ref={ref} {...props} {...useStore(selector, shallow)} />);
}
eg:
import React, { Component } from 'react';
import create from 'zustand';
import shallow from 'zustand/shallow';
function connectZustand(useStore, selector) {
return (Component) =>
React.forwardRef((props, ref) => <Component ref={ref} {...props} {...useStore(selector, shallow)} />);
}
const useStore = create((set) => ({
isPink: false,
setPink: () => set((state) => ({ isPink: !state.isPink })),
}));
class MyClass extends Component {
render() {
const { setPink } = this.props;
return (
<div>
<button onClick={() => setPink()}>Set State Class</button>
</div>
);
}
}
const MyClassWithZustand = connectZustand(useStore, (state) => ({ setPink: state.setPink }))(MyClass);
export default function Test() {
const isPink = useStore((state) => state.isPink);
return (
<>
<MyClassWithZustand />
{isPink ? 'Is Pink' : 'Is Not Pink'}
</>
);
}
Very Simple code , I'hv checked react spelling, ReactDom imported, Please guide me about the error. I am new to the codding world.
import React, { Component } from "react";
import "./App.css";
import { Cardlist } from "./components/cardlist/cardlist.component.jsx";
class App extends Component {
constructor() {
super();
this.state = {
string: "Hello before",
};
}
render() {
return (
<div className="App">
<p>{this.state.string}</p>
<button onClick={() => this.setState({ string: "After text" })}>
Change text
</button>
<Cardlist name="this was prop" />
</div>
);
}
}
export default App;
Cardlist component
import react from "react";
export const Cardlist = (props) => {
console.log(props);
return <div>COngratulations</div>;
};
Try changing that react to React on first line on CardList ?
Hi all I am new to React Here is my code
import React, { Component } from 'react';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
/* eslint-disable import/first */
injectTapEventPlugin();
import './App.css';
import Loginscreen from './Loginscreen'
class App extends Component {
constructor(props){
super(props);
this.state={
loginPage:[],
uploadScreen:[]
}
}
componentWillMount(){
var loginPage =[];
loginPage.push(<Loginscreen parentContext={this}/>);
this.setState({
loginPage:loginPage
})
}
render() {
return (
<div className="App">
{this.state.loginPage}
{this.state.uploadScreen}
</div>
);
}
}
const style = {
margin: 15,
};
export default App;
If i have this line in my code
/* eslint-disable import/first / (in line 5)
then i get an error
'React' must be in scope when using JSX
but if i remove
/ eslint-disable import/first */
then i get following error
Import in body of module; reorder to top import/first
Can you please help me to fix this issue? Thanks in advance
Here is my LoginScreen.js
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import RaisedButton from 'material-ui/RaisedButton';
import Login from './Login';
class Loginscreen extends Component {
constructor(props){
super(props);
this.state={
username:'',
password:'',
loginscreen:[],
loginmessage:'',
buttonLabel:'Register',
isLogin:true
}
}
componentWillMount(){
var loginscreen=[];
loginscreen.push(<Login parentContext={this} appContext={this.props.parentContext}/>);
var loginmessage = "Not registered yet, Register Now";
this.setState({
loginscreen:loginscreen,
loginmessage:loginmessage
})
}
render() {
return (
<div className="loginscreen">
{this.state.loginscreen}
<div>
{this.state.loginmessage}
<MuiThemeProvider>
<div>
<RaisedButton label={this.state.buttonLabel} primary={true} style={style} onClick={(event) => this.handleClick(event)}/>
</div>
</MuiThemeProvider>
</div>
</div>
);
}
}
const style = {
margin: 15,
};
export default Loginscreen;
I'm new for React and Material-UI too. I have this App.js file:
import React, {Component} from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import NavigationMenu from 'material-ui/svg-icons/navigation/menu';
import DrawerMenu from './DrawerMenu';
const AppBarIcon = () => (
<AppBar
title="Title"
iconElementLeft={<IconButton onClick={???}>
<NavigationMenu />
</IconButton>}
/>
);
class App extends Component {
render() {
return (
<div className="App">
<MuiThemeProvider>
<div>
<DrawerMenu />
<AppBarIcon />
</div>
</MuiThemeProvider>
</div>
);
}
}
export default App;
...and this is the DrawerMenu.js file:
import React from 'react';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
export default class DrawerSimpleExample extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle = () => this.setState({open: !this.state.open});
render() {
return (
<div>
<Drawer open={this.state.open}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
</Drawer>
</div>
);
}
}
Is there any way to set the IconButton's onClick value in App.js file to set the DrawerMenu's state open:true ? For example:
<IconButton onClick={ DrawerMenu.setState({open:true}) }>
...or something like this?
You can use props to achieve desired behavior.
Example
const AppBarIcon = (props) => (
<AppBar
title="Title"
iconElementLeft={<IconButton onClick={props.onIconClick}>
<NavigationMenu />
</IconButton>}
/>
);
class App extends Component {
constructor(props) {
super(props);
this.state = { isOpen: false };
}
onIconClick = () => {
this.setState((prevState) => ({ isOpen: !prevState.isOpen }));
}
render() {
return (
<div className="App">
<MuiThemeProvider>
<div>
<DrawerMenu isOpen={this.state.isOpen} />
<AppBarIcon onIconClick={this.onIconClick} />
</div>
</MuiThemeProvider>
</div>
);
}
}
export default class DrawerSimpleExample extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle = () => this.setState({open: !this.state.open});
render() {
return (
<div>
<Drawer open={this.props.isOpen}>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item 2</MenuItem>
</Drawer>
</div>
);
}
}