Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript?

const newRecipe = 
<div id = "container">
<div className="recipe App" id="four" 
onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName}
</div>

<div style={{display:"none"}}>    
{this.state.value4.split(",").map((e)=>
  <p>{e}</p>)}

 <button onClick={this.deleteRecipe}>Delete</button>
<button name="4" onClick={this.openEditBox}>Edit</button>
</div></div>

This hypothetical button would initiate the addition of the above element:

<button onClick={this.newRecipe.bind(this)}>Add Recipe</button>

The corresponding function could look like this:

newRecipe(){
document.body.appendChild({newRecipe});}

Alternatively, some have tried to use 'insertAdjacentElement' as shown below:

newRecipe(){
document.body.insertAdjacentElement("beforeend", {nRecipe});}

However, these attempts resulted in errors such as TypeError. Are there other methods to achieve this without toggling display properties?

Answer №1

It seems like you're trying to display an element when a button is clicked:

  1. Manage element visibility using state:

    constructor(props) {
        super(props);
        this.state = {
         showNewRecipe: false
       };
    }

  1. Create a function to toggle the state

    toggleNewRecipe(){
       this.setState(prevstate => ({
         ...prevState,
       showNewRecipe: !prevstate.showNewRecipe
     }));
    }

  1. Use a logical operator to render the DOM element within JSX:

    {
     this.state.showNewRecipe && (
      "your DOM/JSX element"
     )
    }

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

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

Working efficiently with query selectors in React using useRef

I have created a typewriting effect function and now I am trying to display the code associated with this effect within a specific div element (typingRef). Currently, I am using typingRef.current = letter, but I am wondering if this is equivalent to docu ...

Storing multiple HTML elements in a variable with React allows for easy manipulation and

Looking to optimize some repeated code in a React component that renders HTML elements. Trying to save the repetitive html parts in a variable and then return them, but running into issues. const renderAddress = event => { if (event.venue.address.a ...

What is the best way to keep vue-meta up to date when the route or URL

The issue I am facing is that the meta data on my website does not update when the route changes. Even though the route has a watch function that updates the view correctly, the metaInfo() method from vue-meta fails to keep up with the changes. Below is an ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Obtaining only a portion of the text when copying and editing it

I have a React application where I am attempting to copy text from an HTML element, modify it, and then send it back to the user. I have been successful in achieving this, but I am facing an issue where even if I select only a portion of the text, I still ...

Using jQuery to search for corresponding JSON keys in the PokéAPI

Currently, in my development of an app, I am searching for and implementing an English translation of a language JSON endpoint using the PokéAPI. The challenge lies in identifying the correct location of the English language key within the array response, ...

Obtaining JSON data in a separate JavaScript file using PHP

I have an HTML file with the following content: // target.html <html xmlns="http://www.w3.org/1999/xhtml"> ... <script src="../../Common/js/jquery-ui-1.10.3.js"></script> <script src="../../Common/js/select.js" type="text/javascript"& ...

Trouble with ReactJS render not reflecting changes in get function

Recently, I made some updates to the authentication process on my server for my single-page express/react app. However, when running the express server, I noticed that the updated .get function was not being served by my app. Do you have any ideas on why t ...

Ensure that the HTML link is valid and authenticated using SESSIONS

When creating a website, one of the initial tasks I like to tackle is adding links at the bottom of the page for checking valid HTML and CSS: HTML5  •   CSS <div> <a href="http://validator.w3.org/check?uri=referer" ...

After installing babylonjs via npm, encountering the error 'Unable to utilize import statement outside a module'

Recently, I've been working on setting up babylonjs through npm. Starting with a new project, I ran npm init and then proceeded to install babylonjs using npm install babylonjs --save, following the provided documentation. I then created a JavaScript ...

Using ReactJS to strip HTML tags from JSON response

I'm having trouble figuring out how to strip HTML tags from a JSON response in reactjs. Here's the JSON response: { "price": "26,800.98", "diff": "<!--daily_changing-->+13.44 (+0.05%)&nbsp;& ...

What is the best way to implement a delay before calling the owlCarousel function?

Is there a way to delay calling the owlCarousel function for 5 seconds? I attempted the following: $(document).ready(function(){ setInterval(function(){ $(".demo-slide").owlCarousel(); },5000); }); However, I encountered ...

Troubleshooting problem with Angular Click Outside Directive and unexpected extra click event issue

The challenge I'm facing involves implementing a custom Click Outside Directive for closing modal dialogs, notifications, popovers, and other 'popups' triggered by various actions. One specific issue is that when using the directive with pop ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

Using a table row as a counter in HTML

I am looking for a way to automatically assign IDs to table rows using XSLT in a systematic manner. The idea is to have the ID consist of a string followed by a counter, like this: <table> <tr id="Row1"> # it can be only a number => id=" ...

extracting the ID from within an iframe

Currently, I am developing a script using pure javascript. parent.*nameofiframe*.document.getElementById('error').value; However, when attempting to achieve the same using jQuery, it doesn't seem to work: $('*nameofiframe*', win ...

Utilize recursive and for loop methods for parsing JSON efficiently

I have a JSON file that requires parsing. I'm attempting to implement a recursive method for this task. The current JSON data is structured as shown below: Item 01 SubItem 01 InnerSubItem 01 Item 02 SubItem 01 InnerSubItem 01 Unfortunately, t ...

Challenges when working with AJAX/jQuery in terms of fetching JSON data and setting dataType

I am currently facing a challenge with my practice of AJAX/jQuery coding. Despite my efforts to learn and improve, I find the concepts of jQuery and AJAX quite perplexing. Specifically, I am struggling to understand dataTypes and how to manage different ty ...

What solutions are available to resolve the routing problem in React.js?

On my fourth day working with Node and React.js, I am creating a custom offline search function for Docusaurus 2. I've built a JSON index and implemented a search function using elasticlunr. My goal is to redirect to a separate results page, but I&apo ...