0

Is there a method to use the "document.createElement()" function for an imported element?

Example:

import Box from "./Box"; // import my component

function createFunction(){
    const boxContainer = document.getElementById("boxContainer");
    const createdBox = document.createElement(<Box />); // trying to take my component and creating though a function that I call with a button, but obviously doesn't work

    boxContainer.appendChild(createdBox);
}

My code now:

import Box from "./Box";

function createFunction(){
    const boxContainer = document.getElementById("boxContainer");

    const createdBox = document.createElement("div");
    createdBox.classList.add("box");

    boxContainer.appendChild(createdBox);
}

I want to create a copy of my imported element from a button, without recalling all the things like <p> inside or add calsses etc..

3
  • 1
    If you are using ReactJS, changing DOM with document.createElement() is not a good idea. I think you are not getting the ReactJS way of doing things. Commented Apr 4, 2022 at 21:51
  • 1
    so how can I do that? i'm trying to learn to use React Commented Apr 4, 2022 at 21:59
  • I'd suggest editing the question for clarity. Rather than say create element or copy element, in your title I'd say something like How to Trigger Rendering of Same React Component Multiple Times Inside Another Component which may be closer to what you're asking. I'd update your question to include what you said in your comment describing how you want to trigger a new instance of the component through a button. This isn't very clear in your current question. Doing this will help other users find your question and relevant solution or discussion. Commented Apr 5, 2022 at 7:23

1 Answer 1

1

As mentioned in the comments, you don't need to use the native JS way of controlling the DOM. Instead, your Box component is responsible for what to render. You do this by returning some JSX that represents what you want to render to the DOM.

I added answers to both your questions below. I hope this helps.

Question 1: How to Import and Use Components in React

A simple Box component might look like:

const Box = () => {
  return (
    <div className='box'>Box</div>;
  );
};

export default Box;

Then, you import your Box component to another component where you need it and render it inside that component like so:

import Box from './Box';

const App = () => {

  return (
    <div className='app'>
      <Box />
    </div>
  );
};

export default App;

Question 2: Performing Updates to Add New Items to a List (using State and Props with Components in React)

A useful example of what you're describing is accomplished with state and props along with an understanding of handling events and lifecycle in React.

What data is needed to describe each todo? This will determine the shape of your data for each todo in the list.

Which component should manage the list of todos? This component will keep the todos in state.

Will other components need access to this data? Those components can receive the data as props passed from the parent component.

The below example imagines you have a Box component responsible for displaying each todo in your list. Hopefully this illustrates managing the flow of data and how to add new items to a list and display them.

Object destructuring and spread syntax are used in the example as convenient ways to unpack props and add additional items to state, respectively.

import { useState } from 'react';

const Box = ({ title, description }) => {
  return (
    <div className='todo'>
      <h4>{title}</h4>
      <p>{description}</p>
    </div>
  );
};

const App = () => {
  const defaultFormFields = {
    title: '',
    description: '',
  };

  const [todos, setTodos] = useState([]);
  const [formFields, setFormFields] = useState(defaultFormFields);

  const { title, description } = formFields;

  const addTodo = (event) => {
    event.preventDefault();
    const newTodo = {
      title,
      description,
    };

    setTodos([...todos, newTodo]);
    clearFormFields();
  };

  const clearFormFields = () => {
    setFormFields(defaultFormFields);
  };

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormFields(() => {
      return {
        ...formFields,
        [name]: value,
      };
    });
  };

  return (
    <div>
      <h2>Add Todo</h2>
      <form onSubmit={addTodo}>
        <label>Title</label>
        <input
          onChange={handleChange}
          name='title'
          value={title}
        ></input>
        <label>Description</label>
        <input
          onChange={handleChange}
          name='description'
          value={description}
        ></input>
        <button type='submit'>Add Todo</button>
      </form>
      <h2>Todos</h2>
      {todos.map(({ title, description }) => (
        <Box key={title} title={title} description={description} />
      ))}
    </div>
  );
};

export default App;
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, i've done It like that, but I want to re-create the box, below that box, through a Button, like I manually put <Box /> and below another <Box /> but through a button. Im doing that for trying to make a "todo-app" but with my logic, so without full tutorials etc, but just for practice and learn
See updated answer. You have a couple questions and this is pretty open ended. Next time I'd emphasize describing the single problem you face along with a minimal and complete example. For instance, you're asking a question about React but your sample code contains no React whatsoever. This begs the question, did you attempt to use any React yet? You want a button to add more items. Have you tried adding a button? What do you expect your current code to do? This really helps to narrow down the question so that we can provide more helpful answers :)
yes, that's exactly what I wanted to do! I played around that code for adding things like the showForm button, so the form appears only when i click it, like a modal for mobile app, and a close button for that etc.. now I want to add a delete button for delete de box but can't do that, when I click the delete button he delete the first box, but not the one where i press the button, I can manage to locate the title and the desciption, but can't locate the entire div to delete him
First, search for your question on Stack Overflow. You will find that many working examples and answers to your question already exist. this question is one example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.