What is the process for incorporating a custom React component into our project?

Currently, I am in the process of developing a tasklist React page. I have introduced a new component called "Task". The code snippet below showcases Task.js and mentions that CompletedTask.js contains similar code.

import React,{useState} from 'react'
import Checkbox from '@material-ui/core/Checkbox';
import CompletedTask from './CompletedTask.js';

export default function Task(props){
    const task_text = props.text;

    const complete_text = useState({task_text});

    const taskComplete = (event) => {
        event.preventDefault();
        let doneTask = document.getElementById('done-task-list')

        let new_done_task = document.createElement( <CompletedTask text={complete_text} />);

        doneTask.appendChild(new_done_task);
    }

    return (
        <>
            <Checkbox
                    defaultChecked={false}
                    color="default"
                    inputProps={{ 'aria-label': 'checkbox with default color' }}
                    onClick={taskComplete}
            />
            {task_text}
        </>
    )
}

Further, CompleteTask is an additional React element that I've developed. This element disables the checkbox and changes the text color. However, I'm encountering difficulties in appending this CompleteTask element to the end of my div (identified by id 'done-task'). The issue seems to be related to the usage of document.createElement. Is there an alternative method available for appending a custom element like mine?

Answer №1

A better approach would be to avoid DOM manipulation and ensure you are using the useState hook correctly. Here is a revised version:

import React, { useState } from "react";
import Checkbox from "@material-ui/core/Checkbox";
import CompletedTask from "./CompletedTask.js";

export default function Task(props) {
  const task_text = props.text;

  const [complete, setComplete] = useState(false);

  const taskComplete = () => {
    // Add any additional tasks required to complete the task
    setComplete(true); // This will mark the checkbox as checked and display the completed task component
  };

  return (
    <>
      <Checkbox
        defaultChecked={complete}
        color="default"
        inputProps={{ "aria-label": "checkbox with default color" }}
        onClick={taskComplete}
      />
      {complete && <CompletedTask text={task_text} />}
    </>
  );
}

Answer №2

When it comes to React, there is a distinction between react elements and DOM elements. To make use of the former in the latter, they need to be converted into DOM elements and inserted onto the page using React.createElement(). As someone who is just starting out with React, I recommend utilizing your component <CompletedTask> within the component (<taskComplete>) in the return statement. Employ logical rendering to display <CompletedTask> if it exists.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for displaying a message in an invalid feedback?

I'm having trouble with displaying an error message in the invalid feedback section (confirm password) when the password does not match the confirm password using jQuery. However, even after deleting a single character from the password, the error mes ...

Handsontable: A guide on adding up row values

I have a dynamic number of columns fetched from the database, making it impossible to predict in advance. However, the number of rows remains constant. Here is an illustration: var data = [ ['', 'Tesla', 'Nissan', & ...

Utilize Google Geocoder to Input Coordinates into Specific Fields

Currently, I am on the lookout for a minimalistic Google geocoding script. Most scripts I have come across are quite large and complex, but this one stands out for its simplicity. However, it lacks the feature of automatically inputting the coordinates int ...

Using a forEach loop within an Else statement is ineffective

I've encountered an issue while trying to merge two arrays and create a new one. It seems that my forEach loop inside the else statement is returning undefined. I'm unsure if I made a mistake in my approach or if forEach is not meant to be used w ...

Transmit the file's contents to the user through the Next.js application router

My goal is to send file content to the client using a nextjs app router and route handler. Currently, I have code in place that involves polling on the client side to refresh the content, but I am looking to implement streaming instead. // app/api/route.t ...

aligning a form next to an image side by side

I found this amazing design https://i.sstatic.net/dtO9h.jpg So I decided to implement it with the following code .page-account-box { width: 100%; margin-top: 70px; } .page-account-box .ds-userlogin .account-box { width: 100%; height: auto; p ...

"Incorporating text input from a textbox into a <ul> list

Recently I started a new project which involves adding user-entered text from a textbox into a ul list in Bootstrap. The script for this functionality is placed within the head section of my HTML document. <script type="text/javascript"> fun ...

Two pages with contrasting fonts but identical CSS styling

Within my website, I have utilized the code font-family: 'Caesar Dressing',cursive,"brushsci"; However, it appears that two different fonts are being displayed on two separate pages. Please take a look at the font styles in the header menu of t ...

The compatibility between Babel 7 and the preset-es2015 is not very reliable

After reading this useful tutorial on implementing server-side rendering with create-react-app, I attempted to execute the following code snippet: require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], ...

The specified element at coordinates (x,y) could not be found: solutions for clicking on a series of WebElements individually

Currently, I am tasked with a project that involves taking user input, scraping data from TripAdvisor.it based on that input, storing it in a database, and using machine learning to rearrange the data for future requests. This process aims to offer users c ...

In ASP.Net, looking to execute JavaScript once the update panel finishes loading

Is there a way to trigger a JavaScript function only when the update panel has completely loaded, rather than on the initial page load? I want to be able to scroll once the update panel is fully loaded. If anyone has any suggestions or solutions, please l ...

attempting to communicate with Postman but encountering an error in the process

Upon attempting to send a request through Postman, I encountered an error. Nodemon is operational and the server is active in the terminal. index.server.js file //jshint esversion:6 const express = require("express"); const env = require("d ...

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

Tips on removing an object array in Node.js

I am working on a basic to-do list application using React.js and Node.js without involving a database. I am able to delete elements one by one from the front end, but I need help with deleting them from the Node backend. Can anyone assist me with this? t ...

unable to utilize the clear method on password field using Selenium WebDriver

I am currently testing the validation on a login form using Selenium webdriver. I have noticed that while the username field clears successfully, the password field does not clear when using the clear method. Is there something I am overlooking? it(' ...

Discovering similarities among array elements by looping through an array

Two sets of arrays have values obtained using the data-attribute(data-product-name). One set contains the full list of available items, while the other set consists of selected items associated with a country. <!-- the item list --> <div ...

What is the best way to continuously schedule and execute "get request" commands at regular intervals?

I am currently working on a web application that scrapes news from a news website and then saves it to my database. This scraping process is purely for educational purposes. Once the database is updated, all the stored data is then sent to the user fronten ...

What could be causing the vertical gap between my divs?

My issue revolves around the spacing between three divs on a webpage, where the middle content div is consistently about 50px away from both the header and footer divs. I'm puzzled as to why this separation keeps happening since I haven't define ...

Tips for organizing a dashboard design with Bootstrap

I am looking to design a dashboard using the Bootstrap grid system. Here is the layout I have in mind: https://i.sstatic.net/cqWP5.jpg What would be the optimal way to structure this in the HTML file? Would a layout of 5 rows and 2 columns work best? Th ...