John Gillespie John Gillespie - 2 months ago 12
React JSX Question

React JS - get a variable vlaue to show up in a form field

For the past few days I have been trying to figure out simply how to make default text show up in a form in react. Each div has a "Recipe Title" and I need the unique recipe title for the particular div to show up in the editable field. Nothing that I have watched or read seems to reveal how to do this. Please could someone point me in the right direction?

My CodePen for this project is here.

var GenerateRecipesFromList= React.createClass({
getInitialState: function(){
const defaultData = [["Spaghetti", "pasta, oil, sauce, parsely, cheese"], ["PB&J", "PB, J"]]
const localData = JSON.parse(localStorage.getItem('reclist'));
return {
reclist: localData ? localData : defaultData
}
},

updateRecList: function (reclist) {
this.setState({ reclist: reclist });
},

overlayEdit: function() {
var el2 = document.getElementById("overlay2");
el2.style.visibility = (el2.style.visibility === "visible") ? "hidden" : "visible";
},



render: function(){
var testData = JSON.parse(localStorage.getItem('reclist'));
if(testData === null){
localStorage.setItem('reclist', JSON.stringify(this.state.reclist));
}
var currentData = JSON.parse(localStorage.getItem('reclist'));
var rows = [];

for(var i=0; i<currentData.length; i++){
var thedivname = i;
var recipetitle=currentData[i][0];
console.log(recipetitle);
rows.push(<div id= {this.thedivname} className="individual" onClick= {this.overlayEdit}> <span><h2>{this.state.reclist[i][0]}</h2></span>
</div>);
}
return(
<div className="centerMe" >
<AddButton updateRecList={ this.updateRecList } />
{rows}

<div id="overlay2" recipetitle="recipetitle" >
<div>
<form >
<p>Edit an existing recipe.</p>
Recipe Title: <input type="text" name="title2" id="title2" value={this.recipetitle}>
{
// HOW DO I MAKE "Spaghetti" SHOW UP AS THE DEFAULT TEXT IN THE Recipe Title INPUT AREA WHEN I CLICK THE DIV FOR Spaghetti??????????
}
</input><br/>
Ingredients: <input type="text" name="ingredients2" id="ingredients2"/><br/>
</form>
<p>Click here to <a href='#' onClick={this.overlayEdit}>close</a></p>

</div>
</div>

</div>
);
},
});

var AddButton = React.createClass({

overlayAdd: function() {
var el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility === "visible") ? "hidden" : "visible";
},

exposeAddRecipe: function(){
var exposeCurrentData = [];
var userInput = [];
exposeCurrentData = JSON.parse(localStorage.getItem('reclist'));
var newTitle = document.getElementById("title").value;
var newIngredients = document.getElementById("ingredients").value;

userInput.push(newTitle);
userInput.push(newIngredients);
exposeCurrentData.push(userInput);
localStorage.setItem('reclist', JSON.stringify(exposeCurrentData));
//this.setState({ reclist: exposeCurrentData});
this.props.updateRecList(exposeCurrentData);
this.overlayAdd();
},

render: function(){
return(
<div>
<button type="button" id="btnAdd" onClick={this.overlayAdd}><h2>Add a New Recipe</h2></button>
<div id="overlay">
<div>
<form >
<p>Add a new recipe.</p>
Recipe Title: <input type="text" name="title" id="title">

</input><br/>
Ingredients: <input type="text" name="ingredients" id="ingredients" /> <br/>
<button type="button" className="normalBtn" onClick= {this.exposeAddRecipe}>Save</button>
</form>
<p>Click here to <a href='#' onClick={this.overlayAdd}>close</a></p>

</div>
</div>
</div>
);
}
});

var Footer = React.createClass({
render() {
return (
<footer>
<div id="containerfooter">
<p>Written by <a href="http://codepen.io/profaneVoodoo/full/dXBJzN/">John Gillespie</a> for FreeCodeCamp Campers. Happy Coding!</p>
</div>
</footer>
);
}
});


var MyApp = React.createClass({
render: function() {
return(
<div className = "mainDiv">
<div className="titleDiv">
<h1>Recipe Box</h1>

<GenerateRecipesFromList />
<Footer />
</div>
</div>
);
},
});

ReactDOM.render(
<MyApp />,
document.getElementById('Recipes')
);

Answer

First of all create a new state variable recipe. Then in your onClick function where you add rows pass the recipe name as

rows.push(<div id= {this.thedivname} className="individual" onClick={this.overlayEdit.bind(this, recipetitle)}>

After that in the overlayEdit function set the state variable recipe to be the value as

this.setState({recpe: value})

and then in the form make use of this state variable to set the input as

Recipe Title: <input type="text" name="title2" id="title2" value={this.state.recepi}/>

hope this helps

Complete code

var GenerateRecipesFromList= React.createClass({
    getInitialState: function(){
      const defaultData = [["Spaghetti", "pasta, oil, sauce, parsely, cheese"], ["PB&J", "PB, J"]]
      const localData = JSON.parse(localStorage.getItem('reclist'));
      return {
        reclist: localData ? localData : defaultData,
        recepi: ''
      }
  },  

  updateRecList: function (reclist) {
    this.setState({ reclist: reclist });
  },

  overlayEdit: function(value) {
    this.setState({recepi: value})
      var el2 = document.getElementById("overlay2");
    el2.style.visibility = (el2.style.visibility === "visible") ? "hidden" : "visible";
  },



  render: function(){
    var testData = JSON.parse(localStorage.getItem('reclist'));
    if(testData === null){
        localStorage.setItem('reclist', JSON.stringify(this.state.reclist));
        }
        var currentData = JSON.parse(localStorage.getItem('reclist'));
        var rows = [];

          for(var i=0; i<currentData.length; i++){
        var thedivname = i;
         var recipetitle=currentData[i][0];
            console.log(recipetitle);
          rows.push(<div id= {this.thedivname} className="individual" onClick={this.overlayEdit.bind(this, recipetitle)}> <span><h2>{this.state.reclist[i][0]}</h2></span> 
        </div>);
        }
      return(
        <div className="centerMe" >
          <AddButton updateRecList={ this.updateRecList } />
          {rows}

          <div id="overlay2" recipetitle="recipetitle" >
            <div>
              <form > 
                <p>Edit an existing recipe.</p>
                Recipe Title: <input type="text" name="title2" id="title2" value={this.state.recepi}/>
                <br/>
                Ingredients: <input type="text" name="ingredients2" id="ingredients2"/><br/>
              </form>
              <p>Click here to <a href='#' onClick={this.overlayEdit}>close</a></p>

            </div>
          </div> 

        </div>
      );
    },
});

var AddButton = React.createClass({

      overlayAdd: function() {
        var el = document.getElementById("overlay");
      el.style.visibility = (el.style.visibility === "visible") ? "hidden" : "visible";
      },

      exposeAddRecipe: function(){
          var exposeCurrentData = [];
          var userInput = [];
          exposeCurrentData = JSON.parse(localStorage.getItem('reclist'));
         var newTitle = document.getElementById("title").value;
         var newIngredients = document.getElementById("ingredients").value;

         userInput.push(newTitle);
         userInput.push(newIngredients);
         exposeCurrentData.push(userInput);
          localStorage.setItem('reclist', JSON.stringify(exposeCurrentData));
          //this.setState({ reclist: exposeCurrentData});
        this.props.updateRecList(exposeCurrentData);
         this.overlayAdd();
      },

      render: function(){
      return(
        <div>
          <button type="button" id="btnAdd" onClick={this.overlayAdd}><h2>Add a New Recipe</h2></button> 
            <div id="overlay">
             <div>
                <form > 
                 <p>Add a new recipe.</p>
                 Recipe Title: <input type="text" name="title" id="title">

                  </input><br/>
                 Ingredients: <input type="text" name="ingredients" id="ingredients" /> <br/>
               <button type="button" className="normalBtn" onClick={this.exposeAddRecipe}>Save</button>
               </form>
               <p>Click here to <a href='#' onClick={this.overlayAdd}>close</a></p>

              </div>
            </div> 
          </div>
          );
         }
  });

var Footer = React.createClass({
    render() {
    return (
      <footer>
        <div id="containerfooter">
          <p>Written by <a href="http://codepen.io/profaneVoodoo/full/dXBJzN/">John Gillespie</a> for FreeCodeCamp Campers. Happy Coding!</p>
        </div>
      </footer>
    );
  }
  });


var MyApp = React.createClass({  
  render: function() {
    return(
      <div className = "mainDiv">
          <div className="titleDiv">
        <h1>Recipe Box</h1>

           <GenerateRecipesFromList />
           <Footer />
          </div>        
        </div>
    );
  }, 
}); 

ReactDOM.render(
  <MyApp />,
  document.getElementById('Recipes')
);

CODEPEN DEMO