'ReactDOM' is not defined no-undef - reactjs

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

Related

React Native Error: Invalid hook call. Hooks can only be called inside of the body of a function component

I'm programming with some friends a Chess App and now we get an Error implementing the Chess itself.
we get the error in the first const of the function as well as at the Export of App.jsx
Our GitHub Repo: Chedu
App.jsx
import React, { useEffect, useState } from "react";
import "./App.css";
import { gameSubject, initGame, resetGame } from "./Game";
import Board from "./Board";
function App() {
const [board, setBoard] = useState([]); //get Error here
const [isGameOver, setIsGameOver] = useState();
const [result, setResult] = useState();
const [turn, setTurn] = useState();
useEffect(() => {
initGame();
const subscribe = gameSubject.subscribe((game) => {
setBoard(game.board);
setIsGameOver(game.isGameOver);
setResult(game.result);
setTurn(game.turn);
});
return () => subscribe.unsubscribe();
}, []);
return (
<div className="container">
{isGameOver && (
<h2 className="vertical-text">
GAME OVER
<button onClick={resetGame}>
<span className="vertical-text"> NEW GAME</span>
</button>
</h2>
)}
<div className="board-container">
<Board board={board} turn={turn} />
</div>
{result && <p className="vertical-text">{result}</p>}
</div>
);
}
export default App(); //Error Anonymous Function
in Index.js we are Rendering the function and export it.
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
export default ReactDOM.render(
<React.StrictMode>
<DndProvider backend={HTML5Backend}>
<App />
</DndProvider>
</React.StrictMode>,
document.getElementById("root")
);
serviceWorker.unregister();
And at last we want to render the index.js in our ChessBoardPage
import React, { useState } from "react";
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
Dimensions,
Switch,
} from "react-native"; //components
import ReactDOM from "react-dom";
import cheduLogo from "../Pictures/Logo.png";
import loginPictureBlack from "../Pictures/login.png";
import loginPictureWhite from "../Pictures/login_white.png";
import registerPictureBlack from "../Pictures/register.png";
import registerPictureWhite from "../Pictures/register_white.png";
import userPictureBlack from "../Pictures/user.png";
import userPictureWhite from "../Pictures/user_white.png";
import ChessGame from "./ChessBoard/index";
const windowWidth = Dimensions.get("window").width;
const windowHeight = Dimensions.get("window").height;
const { width } = Dimensions.get("window");
const x = 100;
const y = 200;
export default class TempPage extends React.Component {
state = {
switchValue: false,
backgroundColor: "white",
SwitchLogin: loginPictureBlack,
SwitchRegister: registerPictureBlack,
SwitchUser: userPictureBlack,
SunMoon: "☀️",
ShadowBackgroundColor: "white",
};
handleSwitchBackground = () => {
[...]
}
};
render() {
let { backgroundColor } = this.state;
return (
<View
style={{
windowWidth,
windowHeight,
backgroundColor: this.state.backgroundColor,
}}
>
[...]
{/*Content*/}
<View stlye={{ flex: 1 }}>
<ChessGame />
</View>
</View>
);
}
}
[...]
sometime we have issues in react when using anonymous functions. Since anonymous functions aren’t assigned an identifier (via const/let/var), they aren’t persistent whenever this functional component inevitably gets rendered again. This causes JavaScript to allocate new memory each time this component is re-rendered instead of allocating a single piece of memory only once when using “named functions”
consider refactoring your code as follows
import React, { useEffect, useState } from "react";
import "./App.css";
import { gameSubject, initGame, resetGame } from "./Game";
import Board from "./Board";
const App = () => {
const [board, setBoard] = useState([]); //get Error here
const [isGameOver, setIsGameOver] = useState();
const [result, setResult] = useState();
const [turn, setTurn] = useState();
useEffect(() => {
initGame();
const subscribe = gameSubject.subscribe((game) => {
setBoard(game.board);
setIsGameOver(game.isGameOver);
setResult(game.result);
setTurn(game.turn);
});
return () => subscribe.unsubscribe();
}, []);
return (
<div className="container">
{isGameOver && (
<h2 className="vertical-text">
GAME OVER
<button onClick={resetGame}>
<span className="vertical-text"> NEW GAME</span>
</button>
</h2>
)}
<div className="board-container">
<Board board={board} turn={turn} />
</div>
{result && <p className="vertical-text">{result}</p>}
</div>
);
};
export default App;
I am not sure why you are using HTML tags in react native, which think are not yet supported in App.jsx. You should return a <View/> tag instead of div.

blank page after of making project by create react app

I want to build my project with create react app. But, I encounter a blank page, when I run "yarn start" in project's directory. As others have said, I set "homepage": "." . but that does not work.
Some said router should be set to "hashrouter". Unfortunately, I don't understand how to do that.
This is my code that has used of context for building "themeSwitcher".
index.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import './app.css';
import {themeContext} from './context.js';
function themeSwitcher(){
return (
<themeContext.consumer>
{({Theme,changeTheme}) => (
<input
type="checkbox"
checked={Theme === "dark"}
onChange={() => changeTheme(Theme === "dark" ? "light" : "dark")}
/>
)}
</themeContext.consumer>
);
}
class app extends React.Component {
constructor(props) {
super(props);
this.state = {
Theme: "light",
changeTheme: this.changeTheme
};
}
changeTheme = (Theme) => {
this.setState({
Theme
});
};
render() {
return (
<themeContext.provider value={this.state}>
<div>
<p>this is a switcher theme</p>
<span>Dark mode</span>
<themeSwitcher />
</div>
</themeContext.provider>
);
}
}
ReactDOM.render(<app />, document.getElementById("root"));
context.js:
import React from "react";
export const themeContext = React.createContext({
Theme: "light",
changeTheme: () => {}
});
Why are the components written with small letters? Component names must begin with a capital letter.
If possible then present code from './context.js'
import React from 'react'
import ReactDOM from 'react-dom'
import './app.css'
import { ThemeContext } from './context.js'
function ThemeSwitcher() {
return (
<ThemeContext.Consumer>
{({ theme, toggleTheme }) => (
<input
type="checkbox"
checked={theme === 'dark'}
onChange={toggleTheme}
/>
)}
</ThemeContext.Consumer>
)
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
theme: 'light'
}
}
toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === 'dark'
? 'light'
: 'dark',
}));
}
contextValue = {
theme: this.state.theme,
toggleTheme: this.toggleTheme
}
render() {
return (
<ThemeContext.Provider value={this.contextValue}>
<div>
<p>this is a switcher theme</p>
<span>Dark mode</span>
<ThemeSwitcher />
</div>
</ThemeContext.Provider>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))
You can also use hooks and functional components. The code is cleaner.
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import './app.css'
import { ThemeContext } from './context.js'
const ThemeSwitcher = () => (
<ThemeContext.Consumer>
{({ theme, toggleTheme }) => (
<input
type="checkbox"
checked={theme === 'dark'}
onChange={toggleTheme}
/>
)}
</ThemeContext.Consumer>
)
const App = () => {
const [theme, setTheme] = useState('light')
const toggleTheme = () => setTheme(theme === 'dark' ? 'light' : 'dark')
const contextValue = {
toggleTheme,
theme,
}
return (
<ThemeContext.Provider value={contextValue}>
<div>
<p>this is a switcher theme</p>
<span>Dark mode</span>
<ThemeSwitcher />
</div>
</ThemeContext.Provider>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
context.js code
import React, { createContext } from "react";
export const ThemeContext = createContext({
theme: "light",
toggleTheme: () => {}
});

Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes' React -typescript Context

I'm currently coding a React -typescript App for practising FluentUI (a.k.a Fabric). Issue appears
with my App.tsx component.
import React, { useContext, useState } from 'react';
import logo from './logo.svg';
import './App.css';
import Search from './components/Search';
//import CategoriasProvider from './components/Context/CategoriasContext';
import Title from './components/Title';
import { ListGhostingExample } from '../src/components/DrinkList';
import { PrimaryButton } from 'office-ui-fabric-react';
import { CategoriasContext, ICategoriasContextInterface } from './components/Context/CategoriasContext';
import CategoriasProvider from './components/Context/CategoriasContext';
import axios from 'axios';
import './components/DrinkList.css'
import './components/Search.css'
interface IApp{
items:ICategoriasContextInterface[],
renderList:boolean
}
const App =()=> {
const contextValues=useContext(CategoriasContext);
return(
<CategoriasProvider>
<div className="App">
<div className="search">
<Search name={contextValues?.name} image={contextValues?.image} thumbnail={contextValues?.thumbnail} />
</div>
</div>
</CategoriasProvider>
);
}
export default App;
CategoriasProvider comes from a Context (CategoriasContext.tsx ). CategoriasProvider has the mentioned error Inside of CategoriasProvider there's a Search.tsx Component.Search's works as a "wrapper". Code is:
import React, { useEffect, useState } from 'react';
import { SearchBox,ISearchBoxStyles } from 'office-ui-fabric-react/lib/SearchBox';
import { PrimaryButton, IContextualMenuProps, Stack, IStackTokens, StackItem, initializeIcons } from 'office-ui-fabric-react';
import { ComboBox, DefaultPalette, Dropdown, DropdownMenuItemType, IComboBoxOption, IDropdownOption, IDropdownStyles, IStackItemStyles, SelectableOptionMenuItemType, Toggle } from '#fluentui/react';
import { getGlassesOriginal } from './Utils/Utils';
import axios from 'axios';
import '../Search.css';
import { CategoriasContext, ICategoriasContextInterface } from './Context/CategoriasContext';
initializeIcons();
const Search = (props:ICategoriasContextInterface) => {
//State
const [textContent, setTextContent] = useState("");
const [textBoxDisabled,disableTextBox]=useState(false);
const [comboBoxDisabled,disableComboBox]=useState(true);
const CategoriasContextInSearch=React.useContext(CategoriasContext);
const setTextContentInstate = (e: any) =>{
console.log("Contenido de e" + e.target.value);
setTextContent(e.target.value);
}
const showMessageInConsole = ():void => {
console.log(textContent);
setTextContent("");
}
// Example formatting
const stackTokens: IStackTokens = { childrenGap: 20 };
const searchBoxStyles: Partial<ISearchBoxStyles> = { root: { width: 200 } };
const dropdownStyles: Partial<IDropdownStyles> = {
dropdown: { width: 200 },
};
const options: IDropdownOption[] = [
{ key: 'glasses', text: 'Glasses', itemType: DropdownMenuItemType.Header },
];
function getGlasses () {
let outputArray:string[] = [];
console.log("getGlasses");
axios
.get("https://www.thecocktaildb.com/api/json/v1/1/list.php?g=list")
.then((response)=>{
let responseDataJson=response.data.drinks;
for (let element in responseDataJson) {
options.push({key:responseDataJson[element].strGlass,text:responseDataJson[element].strGlass});
}
}
)
return outputArray;
}
function selectSearch(){
if(textBoxDisabled){
disableTextBox(false);
disableComboBox(true);
} else {
disableTextBox(true);
disableComboBox(false);
};
}
useEffect(() => {
//TODO: No se debería llamar siempre a esta función. Solamente cuando se activa el sistmea de búsqueda (y además, cachearlo)
getGlasses()
});
return(
<div className="wrapper">
<div className="one"> <Toggle onClick={selectSearch}/></div>
<div className="two">
{
<SearchBox
name="searchBox"
className="searchBox"
styles={searchBoxStyles}
placeholder="Cheers!"
onChange={setTextContentInstate}
value={textContent}
disabled={textBoxDisabled}
/>
}
</div>
<div className="three">
<Dropdown
placeholder="Select a glass"
options={options}
styles={dropdownStyles}
disabled={comboBoxDisabled}
/>
</div>
<div className="four">
<div className="primaryButton">
<PrimaryButton text="Search" onClick={showMessageInConsole}/>
</div>
</div>
</div>
);
}
export default Search;
Hope you can help me!!! Thanks in advance!
The code which is causing the error in your title is in your comment. It's this line:
export const CategoriasProvider = () => {
You are defining CategoriasProvider as a component which takes no props. It can only accept IntrinsicAttributes which is basically just the key property.
But when you use CategoriasProvider in App you are calling it with JSX element children. You get an error because you have not said that the CategoriasProvider component can accept a children prop.
Any of the following types will solve your problem:
export const CategoriasProvider: React.FC = ({children}) => {
export const CategoriasProvider = ({children}: {children: React.ReactNode}) => {
export const CategoriasProvider = ({children}: React.PropsWithChildren<{}>) => {
Regardless, you'll want to pass the children down as children of the inner Provider component.
return (
<CategoriasContext.Provider value={hola}>
{children}
</CategoriasContext.Provider>
);
Your App component is not going to work as expected because the useContext hook which accesses the CategoriasContext is located outside of the CategoriasProvider. It will just get the default value for the context -- not the value from the provider.
You need to rearrange your components such that the hook call occurs in a component that is rendered inside of the CategoriasProvider.
Try this:
const Search = () => {
const contextValues = useContext(CategoriasContext);
return (
<div className="search">
<Search
name={contextValues?.name}
image={contextValues?.image}
thumbnail={contextValues?.thumbnail}
/>
</div>
);
};
const App = () => {
return (
<CategoriasProvider>
<div className="App">
<Search />
</div>
</CategoriasProvider>
);
};
export default App;

React-Router-Dom <Link> not render page

I'm building a practice app that uses Unsplash to render users photos. I'm using React and Redux. With react-router-dom, I'm trying to follow the docs but I find it very confusing to set up. Here's what I have so far. When I click on a result out of a returned list of results from a search, I want it to render a user page profile.
index.js (make sure I have react-router-do set up correctly):
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
// import store from './app/store';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import reducers from "./app/reducers/rootReducer";
import * as serviceWorker from './serviceWorker';
const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, storeEnhancers(applyMiddleware(thunk)));
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
Top component App
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Images from "./app/components/Images";
import Search from "./app/components/Search";
import UserProfile from "./app/components/UserProfile";
import "./App.css";
function App() {
return (
<>
<Search />
<Images />
<Router>
<Route link="/userProfile">
<UserProfile />
</Route>
</Router>
</>
);
}
export default App;
search (parent component to searchResults where exists):
import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import { queryAction } from "../actions/queryAction";
import SearchResults from "./SearchResults";
const Search = (props) => {
const [query, setQuery] = useState("");
console.log(props.searches);
const searchPhotos = async (e) => {
e.preventDefault();
console.log("submitting form");
props.queryAction(query);
};
const showUsers = (user, e) => {
e.preventDefault()
console.log(user)
};
return (
<>
<form className="form" onSubmit={searchPhotos}>
<label className="label" htmlFor="query">
{" "}
</label>
<input
type="text"
name="query"
className="input"
placeholder={`Try "dog" or "apple"`}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button type="submit" className="button">
Search
</button>
</form>
<SearchResults results={props.searches} showUsers={showUsers} />
</>
);
};
const mapStateToProps = (state) => {
return {
searches: state.searches,
};
};
const mapDispatchToProps = (dispatch) => {
return {
queryAction: (entry) => dispatch(queryAction(entry)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Search);
searchResults:
import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";
import { getUserAction } from "../actions/getUserAction";
import { connect } from "react-redux";
const SearchResults = (props) => {
const { results } = props.results.searches;
const handleClick = (result, e) => {
e.preventDefault();
props.getUser(result.username);
};
return (
<>
{results &&
results.map((result, id) => {
return (
<div key={id}>
<Router>
<Link to="/userProfile" onClick={(e) => handleClick(result, e)}>
{result.username}
</Link>
</Router>
</div>
);
})}
</>
);
};
const mapDispatchToProps = (dispatch) => {
return {
getUser: (query) => dispatch(getUserAction(query)),
};
};
export default connect(null, mapDispatchToProps)(SearchResults);
and finally the UserProfile component:
import React from 'react';
import { connect } from 'react-redux';
const UserProfile = props => {
console.log(props)
return (
<div>
</div>
);
}
const mapStateToProps = state => {
return {
user: state.users
}
}
export default connect(mapStateToProps, null)(UserProfile);
app component
import React from "react";
import { Switch, Route } from "react-router-dom";
import Images from "./app/components/Images";
import Search from "./app/components/Search";
import UserProfile from "./app/components/UserProfile";
import "./App.css";
function App() {
return (
<>
<Search />
<Images />
<Switch>
<Route path="/userProfile/:username">
<UserProfile />
</Route>
</Switch>
</>
);
}
export default App;
SearchResults component
import React from "react";
import { Link } from "react-router-dom";
const SearchResults = (props) => {
const { results } = props.results.searches;
const handleClick = (result, e) => {
e.preventDefault();
props.getUser(result.username);
};
return (
<>
{results &&
results.map((result, id) => {
return (
<div key={id}>
<Link to={`/userProfile/${result.username}`}>
{result.username}
</Link>
</div>
);
})}
</>
);
};
export default SearchResults;
UserProfile component
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { getUserAction } from "../actions/getUserAction";
const UserProfile = props => {
useEffect(() => {
props.getUserAction(props.match.params.username)
},[])
console.log(props)
return (
<div>
{props.user
? <div>{user.username}</div>
: <div>Loading...</div>
}
</div>
);
}
const mapStateToProps = state => {
return {
user: state.users
}
}
const mapDispatchToProps = (dispatch) => {
return {
getUser: (query) => dispatch(getUserAction(query)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserProfile);
Edit: Add a param to your link and remove the onclick. Update the Route to expect a :username param. You can access the param through props in UserProfile component.
Make sure to perform the action or access state when mounting the UserProfile component so you have some data when it renders.
Edit 2: Added UserProfile component to answer. You want to dispatch your action when the component is mounting. Also, set a ternary to show "Loading..." if state.user isn't done being fetched.

Trying to use getCurrentContent in draftjs file

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')
)

Resources