How to keep track of selections in array of radio button groups? - javascript

I'm baffled over this problem that seems to have a simple solution right under my nose, but I can't find it.
I'm looping 42 groups of radio buttons, and I'm only as yet able to get one (out of 42 * 4 buttons) to be selected. I render the first statement, and each statement has 4 choices... Thank you so much for helping.
import React, { Component } from 'react'
class Acme extends Component {
constructor(props) {
super(props);
this.state = {
selections: [],
statements: "forty-two statements+separated by add signs".split('+')
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
// lost here -- ???
handleChange(event) {
this.state.selections.push( event.target.value )
}
handleSubmit(event) {
event.preventDefault()
alert("Hello")
}
render() {
return (
<div className="pure-form">
<h2>Acme</h2>
<hr />
<h3>
Please read each statement and select a number 0, 1, 2 or 3 which indicates how much the statement applied to you <b>over the past week</b>. There are no right or wrong answers. Do not spend too much time on any statement.
</h3>
<form onSubmit={this.handleSubmit}>
{
this.state.statements.map(
(statement, index) => (
<div className="pure-g">
<div className="pure-u-1 pure-u-md-21-24 pure-control-group">
<h4>{index+1}. {statement}</h4>
<div className="pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={0} key={index}
checked={this.state.selections[index] === 0 }
onChange={this.handleChange} />
0
</label>
</div>
<div className="radio pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={1} key={index}
checked={this.state.selections[index] === 1}
onChange={this.handleChange } />
1
</label>
</div>
<div className="radio pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={2} key={index}
checked={this.state.selections[index] === 2 }
onChange={this.handleChange } />
2
</label>
</div>
<div className="radio pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={3} key={index}
checked={this.state.selections[index] === 3 }
onChange={this.handleChange } />
3
</label>
</div>
</div>
</div>
)
)
}
<button type="submit" className="pure-button pure-button-primary">
See Results
</button>
</form>
</div>
)
}
}
export default Acme

You need to keep a map of selections with the key as the statement id. I have attached the sample code
class Acme extends React.Component {
constructor(props) {
super(props);
this.state = {
selections: {},
statements: "forty-two statements+separated by add signs".split('+')
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
const [id, value] = event.target.value.split('-');
this.setState({
selections: {
...this.state.selections,
[id]: parseInt(value),
}
});
}
handleSubmit(event) {
event.preventDefault()
alert("Hello")
}
render() {
return (
<div className="pure-form">
<h2>Acme</h2>
<hr />
<h3>
Please read each statement and select a number 0, 1, 2 or 3 which indicates how much the statement applied to you <b>over the past week</b>. There are no right or wrong answers. Do not spend too much time on any statement.
</h3>
<form onSubmit={this.handleSubmit}>
{
this.state.statements.map(
(statement, index) => (
<div className="pure-g" key={index}>
<div className="pure-u-1 pure-u-md-21-24 pure-control-group">
<h4>{index+1}. {statement}</h4>
<div className="pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={`${index}-0`} key={`${index}-0`}
checked={this.state.selections[index] === 0 }
onChange={this.handleChange} />
0
</label>
</div>
<div className="radio pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={`${index}-1`} key={`${index}-1`}
checked={this.state.selections[index] === 1}
onChange={this.handleChange } />
1
</label>
</div>
<div className="radio pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={`${index}-2`} key={`${index}-2`}
checked={this.state.selections[index] === 2 }
onChange={this.handleChange } />
2
</label>
</div>
<div className="radio pure-u-5-24">
<label className="pure-radio">
<input type="radio" value={`${index}-3`} key={`${index}-3`}
checked={this.state.selections[index] === 3 }
onChange={this.handleChange } />
3
</label>
</div>
</div>
</div>
)
)
}
<button type="submit" className="pure-button pure-button-primary">
See Results
</button>
</form>
</div>
)
}
}
ReactDOM.render(
<Acme />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>

Related

Reactjs problems with radio buttons when fetch data

I want to build menu for my website with food cards. I fetch data(name of food, recipe, price) from my rest api and then i show this data on my react app. In this food card I have three radio buttons for mini, middle and maxi prices. When I change button on one card it changes on all cards. First image, when price 35 and
Second image, when I change price on first card, but it changes on all cards
this is my code:
constructor(props){
super(props);
this.state = {
shavermas : [],
price : ''
};
}
componentDidMount(){
this.findAllPosts();
}
findAllPosts(){
axios.get("http://localhost:8080/api/shaverma/all")
.then(response => response.data)
.then((data) => {
this.setState({shavermas: data})
});
}
onChange = e =>{
this.setState({price : e.target.value})
}
render(){
let {price} = this.state;
const {shavermas} = this.state;
return(
<>
{shavermas.map((shaverma, index) => (
<div className="food-cart">
<div className="product-img-div">
<img
src={shavermaPhoto}
className="d-inline-block product-img"
alt="shaverma"
/>
</div>
<div className="food-cart-body">
<div>
<h3>Шаверма <span>{shaverma.foodName}</span></h3>
<p>{shaverma.recipe}</p>
<form className="radio-buttons">
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMini} onChange={this.onChange} checked={price.charAt(0) == '' ? shaverma.priceMini : price == shaverma.priceMini}/>
<span>Mini</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMiddle} onChange={this.onChange} checked={price == shaverma.priceMiddle}/>
<span>Middle</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMaxi} onChange={this.onChange} checked={price == shaverma.priceMaxi} />
<span>Maxi</span>
</label>
</div>
</form>
<div className="food-cart-footer">
<strong>{price.charAt(0) === '' ? shaverma.priceMini : price}₴</strong>
<p>Хочу!</p>
</div>
</div>
</div>
</div>
))}
</>
)
}
You are using common Price state for all cards, you have to use price property for individual card,
Use it like this :
onChange = (e,index) =>{
let newShavermas = this.state.shavermas ;
newShavermas[index].price=e.target.value;
this.setState({price : e.target.value})
}
and while fetching the result include price property in each record
findAllPosts(){
axios.get("http://localhost:8080/api/shaverma/all")
.then(response => response.data)
.then((data) => {
let dataVal = data.map(ele=>ele.Price='');
this.setState({shavermas: dataVal })
});
}
and in return call onChange like this :
return(
<>
{shavermas.map((shaverma, index) => (
<div className="food-cart">
<div className="product-img-div">
<img
src={shavermaPhoto}
className="d-inline-block product-img"
alt="shaverma"
/>
</div>
<div className="food-cart-body">
<div>
<h3>Шаверма <span>{shaverma.foodName}</span></h3>
<p>{shaverma.recipe}</p>
<form className="radio-buttons">
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMini} onChange={(e)=>this.onChange(e,index)} checked={shaverma.price.charAt(0) == '' ? shaverma.priceMini : price == shaverma.priceMini}/>
<span>Mini</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMiddle} onChange={(e)=>this.onChange(e,index)} checked={shaverma.price == shaverma.priceMiddle}/>
<span>Middle</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMaxi} onChange={(e)=>this.onChange(e,index)} checked={shaverma.price == shaverma.priceMaxi} />
<span>Maxi</span>
</label>
</div>
</form>
<div className="food-cart-footer">
<strong>{shaverma.price.charAt(0) === '' ? shaverma.priceMini : shaverma.price}₴</strong>
<p>Хочу!</p>
</div>
</div>
</div>
</div>
))}
</>
)
This is because all of you cart items are looking at the same state value!
onChange = e =>{
this.setState({price : e.target.value}) < --- changes price to all cards
}
To solve this, you will need to have a price inside each shaverma then change it alone.
I would suggest starting by creating a FootCart component with its own state.
Something along the line of:
class FootCart implements React.Component {
...
render() {
return (
<div className="food-cart">
...
</div>
}
}
class Cards implements React.Component {
...
render(){
return (
<>
{shavermas.map((shaverma, index) => (<FootCart props/>)}
</>
}
}
Good Luck!

Adding array elements through multiple form fields in React

I am working on a quiz app project to learn to react. I came across a situation where I need to store incorrect options in a quiz question in an array. And later pass over the information to the database.
This is an example JSON format.
{
incorrect_answers:["Jeff Bezos","Satya Nadela","Bill Gates"] }
The incorrect answer is an array and the value needs to be inputted through separate text boxes for each incorrect option like this.
option input form
The part where I am stuck is appending them to the array here is my attempt.
export default class CreateQuiz extends Component{
constructor(props){
super(props);
this.onChangedIncorrectAnswer=this.onChangedIncorrectAnswer.bind(this);
this.onSubmit=this.onSubmit.bind(this);
this.state={
incorrect_answers:[]
}
}
onChangedIncorrectAnswer(e){
const option=e.target.value
this.setState({
incorrect_answers:[...this.state.incorrect_answers,option]
});
}
onSubmit(e){
e.preventDefault();
const quiz = {
incorrect_answers:this.state.incorrect_answers
}
console.log(quiz);
axios.post("http://localhost:3000/quizes",quiz)
.then(res=>console.log(res.data));
window.location='/quiz-list';
}
render(){
return (
<div>
<h3>Create New Quiz</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Incorrect Option 1</label>
<input type="text"
required
className="form-control"
value={this.state.incorrect_answers[0]}
onChange={this.onChangedIncorrectAnswer}
/>
</div>
<div className="form-group">
<label>Incorrect Option 2</label>
<input type="text"
required
className="form-control"
value={this.state.incorrect_answers[1]}
onChange={this.onChangedIncorrectAnswer}
/>
</div>
<div className="form-group">
<label>Incorrect Option 3</label>
<input type="text"
required
className="form-control"
value={this.state.incorrect_answers[2]}
onChange={this.onChangedIncorrectAnswer}
/>
</div>
<div className="form-group">
<input type="submit" value="Submit Quiz" className="btn btn-primary"/>
</div>
</form>
</div>
)
}
}
But the form was not working as expected. When I enter content for the first option in the "Option 1" text box only the first character is stored remaining in "Option 2" and so on.
try this, this would work!!
export default class CreateQuiz extends Component {
constructor(props) {
super(props);
this.onChangedCorrectAnswer = this.onChangedCorrectAnswer.bind(this);
this.onChangedIncorrectAnswer = this.onChangedIncorrectAnswer.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
category: "",
correct_answer: "",
difficulty: "",
type: "",
question: "",
incorrect_answers: ["", "", ""]
};
}
onChangedCorrectAnswer(e) {
this.setState({
correct_answer: e.target.value
});
}
onChangedIncorrectAnswer(e, index) {
const option = e.target.value;
const { incorrect_answers } = this.state;
incorrect_answers[index] = option;
this.setState({
incorrect_answers
});
}
onSubmit(e) {
e.preventDefault();
const quiz = {
category: this.state.category,
correct_answer: this.state.correct_answer,
incorrect_answers: this.state.incorrect_answers,
difficulty: this.state.difficulty,
type: this.state.type,
question: this.state.question
};
console.log(quiz);
axios
.post("http://localhost:3000/quizes", quiz)
.then((res) => console.log(res.data));
window.location = "/quiz-list";
}
render() {
return (
<div>
<h3>Create New Quiz</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Correct Answer</label>
<input
type="text"
required
className="form-control"
value={this.state.correct_answer}
onChange={this.onChangedCorrectAnswer}
/>
</div>
<div className="form-group">
<label>Incorrect Option 1</label>
<input
type="text"
required
className="form-control"
value={this.state.incorrect_answers[0]}
onChange={(e) => this.onChangedIncorrectAnswer(e, 0)}
/>
</div>
<div className="form-group">
<label>Incorrect Option 2</label>
<input
type="text"
required
className="form-control"
value={this.state.incorrect_answers[1]}
onChange={(e) => this.onChangedIncorrectAnswer(e, 1)}
/>
</div>
<div className="form-group">
<label>Incorrect Option 3</label>
<input
type="text"
required
className="form-control"
value={this.state.incorrect_answers[2]}
onChange={(e) => this.onChangedIncorrectAnswer(e, 2)}
/>
</div>
<div className="form-group">
<input
type="submit"
value="Submit Quiz"
className="btn btn-primary"
/>
</div>
</form>
</div>
);
}
}
Your array state is considered as one state only
Why don't you create state on the go when user do any change in the input.
create a state object like
this.state = {incorrect_answers: {}}
In your onChangedIncorrectAnswer
onChangedIncorrectAnswer(e){
const option=e.target.value;
const stateName = e.target.name;
this.setState({
incorrect_answers: {...this.state.incorrect_answers, [stateName]: option }
});
}
use your form element as add name as unique which will be used as state
<div className="form-group">
<label>Incorrect Option 1</label>
<input name="incorrect_answers_0" type="text" required className="form-control" value={this.state.incorrect_answers[incorrect_answers_0]}
onChange={this.onChangedIncorrectAnswer} />
</div>
use that object while saving
onSubmit(e){
let yourIncorrectAnswers = Object.values(this.state.incorrect_answers);
})
}

ReactJS TypeError: Cannot read property 'setState' of undefined even after binding in the constructor and also using the arrow function

I'm getting the error at line 116
checked={this.setState({selectedOption: "Male"})}
If I remove that line, then I get the same error at the next line.
import React, { Component } from "react";
import { Document, Page } from "react-pdf";
import { pdfjs } from 'react-pdf';
import SplitPane, { Pane } from 'react-split-pane';
import { Button } from 'react-bootstrap';
import axios from 'axios';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
export class TestPage extends React.Component{
constructor(props){
super(props);
this.state = {
numPages: null,
pageNumber: 1,
items: [],
responses: [],
color: '',
name: "React",
selectedOption: "Male",
};
this.onValueChange = this.onValueChange.bind(this);
this.formSubmit = this.formSubmit.bind(this);
this.goToPrevPage = this.goToPrevPage.bind(this);
this.goToNextPage = this.goToNextPage.bind(this);
this.onDocumentLoadSuccess = this.onDocumentLoadSuccess.bind(this);
}
componentDidMount(){
axios.get("http://localhost:5000/getquestiondata")
.then(
(result) => {
this.setState({
items: result.data.number,
});
}).catch(error => {
console.log("Error: ", error)
})
}
onDocumentLoadSuccess = ({ numPages }) => {
this.setState({ numPages: numPages });
};
formSubmit = event => {
event.preventDefault();
console.log(this.state.selectedOption);
}
onValueChange = event =>{
this.setState({
selectedOption: event.target.value
});
}
goToPrevPage = () =>
this.setState(state => ({ pageNumber: state.pageNumber - 1 }));
goToNextPage = () =>
this.setState(state => ({ pageNumber: state.pageNumber + 1 }));
render() {
const { pageNumber, numPages, items } = this.state;
var quesNos = [];
// var resp = [];
for(var i = 0; i < items; i++){
quesNos.push(i);
// resp.push(i);
}
console.log("QuesNos: ",quesNos);
return (
<div>
<h1 style={{textAlign: "center"}}>Online Test #1</h1>
<hr />
<SplitPane
split="vertical"
sizes={[50,50]}
defaultSize={parseInt(localStorage.getItem('splitPos'), 10)}
onChange={size => localStorage.setItem('splitPos', size)}
style={{overflow: 'scroll'}}
>
<div style={{overflowY: 'scroll', height:'100%', overflowX: 'scroll'}}>
<nav>
<button onClick={this.goToPrevPage}>Prev</button>
<button onClick={this.goToNextPage}>Next</button>
</nav>
<div>
<Document
file={require('./sample.pdf')}
onLoadSuccess={this.onDocumentLoadSuccess}
>
<Page pageNumber={pageNumber}/>
</Document>
</div>
<p>
Page {pageNumber} of {numPages}
</p>
</div>
<div style={{overflowY: 'scroll', height:'100%', overflowX: 'scroll'}}>
<form onSubmit={this.answerSubmit}>
{quesNos.map(function(qno){
return(
<div>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={this.setState({selectedOption: "Male"})}
onChange={this.onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={this.state.selectedOption === "Female"}
onChange={this.onValueChange}
/>
Female
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Other"
checked={this.state.selectedOption === "Other"}
onChange={this.onValueChange}
/>
Other
</label>
</div>
<div>
Selected option is : {this.state.selectedOption}
</div>
<Button variant="btn btn-primary" type="submit">Submit</Button>
</div>
);
})}
<Button variant='primary' type="submit">Submit</Button>{' '}
</form>
</div>
</SplitPane>
</div>
);
}
}
Any idea why this error happens and how to fix it?
Thanks!
Two errors in your code
Your map function must be an arrow function to leverage this of the class/ or you use .bind for the map function
You must not setState directly in render. I assume you meant to compare state with checked attribute like checked={this.state.selectedOption === "Male"}
Updated code below
{quesNos.map((qno) => { // arrow function here
return(
<div>
<div className="radio">
<label>
<input
type="radio"
value="Male"
checked={this.state.selectedOption === "Male"} // Comparison here
onChange={this.onValueChange}
/>
Male
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Female"
checked={this.state.selectedOption === "Female"}
onChange={this.onValueChange}
/>
Female
</label>
</div>
<div className="radio">
<label>
<input
type="radio"
value="Other"
checked={this.state.selectedOption === "Other"}
onChange={this.onValueChange}
/>
Other
</label>
</div>
<div>
Selected option is : {this.state.selectedOption}
</div>
<Button variant="btn btn-primary" type="submit">Submit</Button>
</div>
);
})}

Radio button global state for name attribute

I need to be able to have radion buttons or checkboxes to show / hide content if its checked. There will be more radio buttons and checkboxes to show content in the same form, so to distinguish them from each other, it could be based on the name attribute.
So far i can show the hidden fields when i check the radio buttons, but i want one to cancel out the other, but only if it has the same name attribute (something else can also work).
Is there a react genius who can figure this out? I would be forever in your debt :)
class PartnerRoute extends Component {
constructor(props) {
super(props)
this.state = {
showOneTimeFee: '',
showSubscription: ''
};
}
toggleOneTimeFee = () => {
const currentState = this.state.showOneTimeFee;
this.setState({
showOneTimeFee: !currentState
})
}
toggleSubscription = () => {
const currentState = this.state.showSubscription;
this.setState({
showSubscription: !currentState
})
}
render() {
return (
<div className="partner-route">
<ContentContainer>
<div className="form--create-event">
<form>
<h3>Event information</h3>
<GridContainer columnCount="one">
<CustomInput type="text" placeholder="Event name" />
</GridContainer>
<GridContainer columnCount="one">
<CustomTextarea type="text" placeholder="Event description" />
</GridContainer>
<h3>Event date</h3>
<GridContainer columnCount="three">
<CustomInput type="text" placeholder="Day" />
<CustomInput type="text" placeholder="Month" />
<CustomInput type="text" placeholder="Year" />
</GridContainer>
<h3>Payment</h3>
<GridContainer columnCount="one">
<CustomRadio
type="radio"
name="payment"
id="rb1"
value="1"
label="Free, no payment needed"
/>
<CustomRadio
type="radio"
name="payment"
id="rb2"
value="2"
label="1 time fee"
onChange={this.toggleOneTimeFee}
/>
{this.state.showOneTimeFee &&
<div className="hidden-field">
<CustomInput type="text" placeholder="Price" />
</div>
}
<CustomRadio
type="radio"
name="payment"
id="rb3"
value="3"
label="Subscription"
onChange={this.toggleSubscription}
/>
{this.state.showSubscription &&
<div className="hidden-field">
<CustomInput type="text" placeholder="Price" />
</div>
}
</GridContainer>
</form>
</div>
</ContentContainer>
</div>
)
}
}
export default PartnerRoute
Please check this example where I used setState with prevState that is important and also I used changeHandler for all three radio. Moreover, to run this code in my side I changed all Custom input with generic input for ex CustomInput to input. Please revert this your side.
import React, {Component} from "react";
export default class PartnerRoute extends Component {
constructor(props) {
super(props);
this.state = {
showOneTimeFee: false,
showSubscription: false
};
}
handleChange = (event) => {
if (event.target.value == 2) // One Time Fee
this.setState(prevState => {
return {
showOneTimeFee: !prevState.showOneTimeFee,
showSubscription: false
};
});
else if (event.target.value == 3) // Subscription
this.setState(prevState => {
return {
showOneTimeFee: false,
showSubscription: !prevState.showSubscription
};
});
else // Free, no payment needed
this.setState({
showOneTimeFee: false,
showSubscription: false
});
};
render() {
return (
<div className="partner-route">
<div>
<div className="form--create-event">
<form>
<h3>Event information</h3>
<div>
<input type="text" placeholder="Event name"/>
</div>
<div>
<input type="text" multiline="true" placeholder="Event description"/>
</div>
<h3>Event date</h3>
<div>
<input type="text" placeholder="Day"/>
<input type="text" placeholder="Month"/>
<input type="text" placeholder="Year"/>
</div>
<h3>Payment</h3>
<div>
<input type="radio" name="payment" id="rb1" value="1" label="Free, no payment needed"
onChange={this.handleChange}/>
<label htmlFor="rb1">Free, no payment needed</label><br/>
<input type="radio" name="payment" id="rb2" value="2" label="1 time fee"
onChange={this.handleChange}/>
<label htmlFor="rb2">1 time fee</label><br/>
{this.state.showOneTimeFee &&
<div className="hidden-field">
<input type="text" placeholder="One Time Price"/>
</div>
}
<input type="radio" name="payment" id="rb3" value="3" label="Subscription"
onChange={this.handleChange}/>
<label htmlFor="rb3">Subscription</label><br/>
{this.state.showSubscription &&
<div className="hidden-field">
<input type="text" placeholder="Subscription Price"/>
</div>
}
</div>
</form>
</div>
</div>
</div>
)
}
}

Select List not working in ReactJS

I am facing a problem with the select list the onChange event is not being triggered. I can't set the value selected from the select list in this.state variable. Any help will be appreciated.
class SelectActivity extends React.Component{
render(){
return (
<select value={this.props.value} onChange={() =>{this.props.onSelect()}}> {this.props.items.map((item,index) =>{
return <option value={index}>{item}</option>})}
</select>
)
}
}
class Form extends React.Component{
constructor(props){
super(props)
this.state = {first:"",last:"",activity:0,restriction:{a:false,b:false,c:false}}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event){
this.setState({[event.target.name]:event.target.value},()=>{console.log(this.state)})
}
handleCheck(key) {
return function (event) {
var restriction = Object.assign({},this.state.restriction);
restriction[key] = event.target.checked;
this.setState({restriction:restriction},()=>{console.log(this.state)});
}.bind(this);
}
render(){
return(
<form>
<div>
First Name<input name="first" value={this.state.first} onChange={this.handleChange}/>
</div>
<div>
Last Name<input name="last" value={this.state.last} onChange={this.handleChange}/>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.a} onChange={this.handleCheck("a")}/>
<label>a) Dietarty Restriction</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.b} onChange={this.handleCheck("b")}/>
<label>b) Physical Disablities</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.c} onChange={this.handleCheck("c")}/>
<label>c) Medical Needs</label>
</div>
<div>
<SelectActivity name="activity" items={["Science Lab","Swimming","Painting","Cooking"]} value={this.state.activity} onSelect={this.handleChange}/>
</div>
</form>
)
}
}
ReactDOM.render(
<Form/>,
document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="root"></div>
You are not sending the event that is triggered on change of your select input, but you are just calling the function with
onChange={ () => {this.props.onSelect()} }
Also, you didn't have any name assigned to your select input.
Please update your select input to:
<select
value={this.props.value}
name={this.props.name}
onChange={this.props.onSelect} // assigning the function, so it can be trigged with all argument
>
{
this.props.items.map((item,index) => {
return <option value={index}>{item}</option>
})
}
</select>
class SelectActivity extends React.Component{
render(){
return (
<select value={this.props.value} name={this.props.name} onChange={this.props.onSelect}> {this.props.items.map((item,index) =>{
return <option value={index}>{item}</option>})}
</select>
)
}
}
class Form extends React.Component{
constructor(props){
super(props)
this.state = {first:"",last:"",activity:0,restriction:{a:false,b:false,c:false}}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event){
this.setState({[event.target.name]:event.target.value},()=>{console.log(this.state)})
}
handleCheck(key) {
return function (event) {
var restriction = Object.assign({},this.state.restriction);
restriction[key] = event.target.checked;
this.setState({restriction:restriction},()=>{console.log(this.state)});
}.bind(this);
}
render(){
return(
<form>
<div>
First Name<input name="first" value={this.state.first} onChange={this.handleChange}/>
</div>
<div>
Last Name<input name="last" value={this.state.last} onChange={this.handleChange}/>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.a} onChange={this.handleCheck("a")}/>
<label>a) Dietarty Restriction</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.b} onChange={this.handleCheck("b")}/>
<label>b) Physical Disablities</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.c} onChange={this.handleCheck("c")}/>
<label>c) Medical Needs</label>
</div>
<div>
<SelectActivity name="activity" items={["Science Lab","Swimming","Painting","Cooking"]} value={this.state.activity} onSelect={this.handleChange}/>
</div>
</form>
)
}
}
ReactDOM.render(
<Form/>,
document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="root"></div>

Categories

Resources