Uncaught TypeError: ReactDOM is undefined

28 Views Asked by At

Hi everyone,I have some issues with my React Code and i can't use the ReactDom because the console says that 'Uncaught TypeError: ReactDOM is undefined'. This is my code and begins with my first component AddTasks :

    import { useState } from "react"
    import ShowOrDelete from "../ShowOrDelete"
    import React from 'react'

    const AddTasks = () =>{
        const [tasks, setTasks] = useState('')
        const placeHolderText = "Escribe algo aqui"
    

    return(
        <div className="bg-slate-200 p-8 mt-36 m-auto w-1/2 h-96 rounded-lg text-2xl text-center" id="task-container">
            <h2 className="mb-8"><strong>Mis Tareas</strong></h2> 
            <div>
                <input className="h-10" type="text" name="tasks" id="input-value" placeholder={placeHolderText}/>
                <ShowOrDelete insertTasks={setTasks} tasks={tasks}/>
            </div>

        </div>
    )
    }

    export default AddTasks

Next this is the next Component that must to render and where i have the issue.

import React from 'react'
import ReactDOM from 'react-dom/client'



const ShowOrDelete = ({ insertTasks, tasks }) =>{
    const addTasksToComplete = () =>{
        const input = document.getElementById('input-value').value;
        insertTasks(input)
        const tasksDiv = <div className="bg-slate-950 text-white text-xl"><p>{tasks}</p></div>;
        ReactDOM.render(
            tasksDiv,
            document.getElementById('task-container')
        )
    }

    return(
        <div className="inline">
            <button onClick={() => addTasksToComplete(insertTasks, tasks)} className="bg-green-500 text-white text-xl p-2">Agregar Tareas</button>
        </div>
    )
     }


    export default ShowOrDelete

But then in the console of the localhost show me the message of the title. So what i can do to resolve this or what is the issues?

1

There are 1 best solutions below

0
0stone0 On

Only your index.js should contain a ReactDOM.render(), all deeper components should just render there UI by providing a return().

Same goes for document.getElementById, you should only use that once in index.js to get the React root element, in deeper components, those getElement** function are almost always a bad idea


const { useState } = React;

const Component1 = () => {
    return (
        <div>
            I'm Component - 1!
            <Component2 />
        </div>
    )
}

const Component2 = () => {
    return (
        <div>
            I'm Component - 2!
            <h3>I don't use ReactDOM, I just return what to render!</h3>
        </div>
        
    )
}

// This is in Index.js
ReactDOM.render(<Component1 />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>