0

I have an element that I want to add to the end of my body:

const nRecipe = 
<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>

The button that creates this element is as follows:

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

The function is defined as follows:

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

I have also tried

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

The error messages I get is TypeError:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

&&

TypeError: Failed to execute 'insertAdjacentElement' on 'Element': 
parameter 2 is not of type 'Element'.

I wasn't able to find any question that answers this directly. I do not wish to toggle between showing and hiding elements, I want a button that can create elements defined by jsx using document object model methods.

George Salamanca
  • 180
  • 1
  • 3
  • 11
  • Have you tried using `ReactDOM.render(element, document.getElementById('root'));`? What you can do here is do your `document.body.insertAdjacentElement` call, save that element and pass it as the second argument into ReactDOM.render – TKoL Mar 07 '18 at 16:12
  • I tried removing the brackets and received the same error. I dont want to toggle between showing and hiding, I want a button that I can use to create elements. This was referring to a comment that was recently deleted – George Salamanca Mar 07 '18 at 16:21

1 Answers1

0

It looks like your trying to show an element when youre clicking a button:

  1. Use a state to manage element visibility:

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

  1. Use a function to toggle the state

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

  1. Use a logical operator to render the dom element anywhere in the JSX:

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

  • I do not wish to toggle between show and hide, I could use element.style.display = "block" || "none" for the same purpose. I want a button that can create as many elements as the user wants with this formatting – George Salamanca Mar 07 '18 at 16:50
  • Why not just iterate over the block, limiting to the number of elements required? see: https://stackoverflow.com/questions/22876978/loop-inside-react-jsx?rq=1 – Sebastian Scholle Mar 08 '18 at 07:36