Gaurav Soni Gaurav Soni - 2 months ago 7
React JSX Question

Appending value using React.js

I made todo app using jquery and now using react making same app. I made general layout of the app using react but facing problem in appending element by clicking button. The code i made in jquery was.

function entervalue()
{
var text = $('#inputext').val();
$("#list").append('<li class="item"> <input type="checkbox" class="option-input checkbox"> ' + text + '<button class="destroy"></button><li>');
$("#inputext").val('');
}


Here the value of input field is stored in var text.
List is appended in having checkbox, 'text' and a button.
I want same code to be written in react, so that when i click on button the following list gets appended.

Answer

Use state to store the new value. Save it as an array. React does a re-render when the state changes. During that render, map() through the value in the state and generate the HTML out of it.

this.setState({ //put this inside the 'onChange' handler of <input/>
 value: e.target.value
})

This will set the new value to the state.

var todo = this.state.value.map(function(value){
 return <li class="item"> <input type="checkbox" class="option-input checkbox">{value}<button class="destroy"></button><li>
})

todo will have the latest list of user inputs.

[UPDATE]

Check the example https://jsfiddle.net/Pranesh456/1veb7bdg/1/