boolean state variable change causes parent component to disappear? - javascript

What I currently have is a parent component called WhatDo.tsx that has a button which should open a child component called AddToWardrobe.tsx, which is currently simply a form to be filled out. To do this, I've used a { boolean ? ( show AddToWardrobe component):(show button to open component)}. However, when I click on the button, instead of opening the AddToWardrobe component, everything disappears from the page including the WhatDo component.
Here is the function for WhatDo.tsx(note that there are two placeholders for future buttons):
export default function WhatDo() {
const [showATW, setShowATW] = useState(false);
return(
<div className="WhatDo">
<div className="ActionNavText">
What would you like to do?
</div>
<div className="ActionNavButtons">
<button id="actionbutton">placeholder</button>
<div className="Show__ATW">
{showATW?
<div className = "ATW__shown">
<AddToWardrobe onSubmit={postNewItem}/>
<button onClick ={() => setShowATW(false)}>Nvm!</button>
</div>
:
<button id="actionbutton" onClick={() => {setShowATW(true)}}>Add to your Wardrobe</button>
}
</div>
<button id="actionbutton">placeholder</button>
</div>
<div className="SignOutButton">
<button onClick={signOut}>sign out?</button>
</div>
</div>
)
}
and here is the function for AddToWardrobe.tsx:
interface Props {
onSubmit:(Item: Item) => void;
}
export default function AddToWardrobe({onSubmit}: Props) {
const [itemType, setItemType] = useState<string[]>([]);
const [itemPrinted, setItemPrinted] = useState(false);
const [itemColor, setItemColor] = useState<string[]>([]);
const [secondaryColor, setSecondaryColor] = useState<string[]>([]);
//type check boxes
const [accessoryBox, setAccessoryBox] = useState(false);
const [topBox, setTopBox] = useState(false);
const [bottomBox, setBottomBox] = useState(false);
const [shoeBox, setShoeBox] = useState(false);
const handleTypeSet = (e: any) => {
const typeValue = e.target.value;
// check for item type
if(typeValue === "Accessory") {
setItemType(e.target.checked);
}
if(typeValue === "Top") {
setItemType(e.target.checked);
}
if(typeValue === "Bottom") {
setItemType(e.target.checked)
}
if(typeValue === "Shoes") {
setItemType(e.target.checked);
}
}
//check whether or not printed
const handlePrintChange = (e: any) => {
const printValue = e.target.value;
if (printValue === true) {
setItemPrinted(e.target.checked);
} // else false, I guess?
}
function handleSubmit(e:FormEvent) {
e.preventDefault();
const CurrentItem: Item = {
type: itemType,
printed: itemPrinted,
primaryColor: itemColor,
secondaryColor: secondaryColor,
}
onSubmit(CurrentItem);
//probably here the addtowardrobe component will close/return to main screen
// display a message that says if the item was added successfully or not
}
return (
<div className = "AddToWardrobe">
<form onSubmit={handleSubmit}>
<label className = "ATW__question">What would you like to add?</label>
<div className="ATW__input">
<input type="checkbox" value="Accessory" onChange={handleTypeSet} checked={accessoryBox}>Accessory</input>
<input type="checkbox" value="Top" onChange={handleTypeSet} checked={topBox}>Top</input>
<input type="checkbox" value="Bottom" onChange={handleTypeSet} checked={bottomBox}>Bottom</input>
<input type="checkbox" value="Shoes" onChange={handleTypeSet} checked={shoeBox}>Shoes</input>
</div>
<label>Is this item printed, textured, or solid?</label>
<div className="ATW__primarycolor">
<input type="checkbox"></input>
</div>
<input className='submit' type="submit"value ="Submit"/>
</form>
</div>
)
}
It may be worth noting that the form for AddToWardrobe is also not AS complete as it's going to be, but I feel like clicking on the button should be rendering something, or at the very least not making the entire parent component disappear!

<input> cannot have children. But in AddToWardrobe Component , you are enclosing text in <input>
<div className="ATW__input">
<input type="checkbox" value="Accessory" onChange={handleTypeSet} checked={accessoryBox}>Accessory</input>
<input type="checkbox" value="Top" onChange={handleTypeSet} checked={topBox}>Top</input>
<input type="checkbox" value="Bottom" onChange={handleTypeSet} checked={bottomBox}>Bottom</input>
<input type="checkbox" value="Shoes" onChange={handleTypeSet} checked={shoeBox}>Shoes</input>
</div>
instead use it like this
<div className="ATW__input">
<input type="checkbox" value="Accessory" onChange={handleTypeSet} checked={accessoryBox} />
<input type="checkbox" value="Top" onChange={handleTypeSet} checked={topBox} />
<input type="checkbox" value="Bottom" onChange={handleTypeSet} checked={bottomBox}/>
<input type="checkbox" value="Shoes" onChange={handleTypeSet} checked={shoeBox}/>
</div>

Related

I'm trying to display my questions after I have filtered them from a key that is an difficulty in my Array

There is a total of 30 questions in the array divided into 3 categories easy, medium and hard. Currently, the last 9 questions are showing the difficult questions when their box is checked and the quiz is started. the first question always shows the HTML placeholder that is in my index.html. Wondering if anyone can have a look at it to see where I am going wrong. If you need any more information let me know.
let pickDifficulty = () => {
if (easyDifficulty.checked) {
difficultyLevel = "easy";
} else if (mediumDifficulty.checked) {
difficultyLevel = "medium";
} else if (hardDifficulty.checked) {
difficultyLevel = "hard";
}
};
function displayQuestion(quizQuestion, quiz) {
quizQuestion.querySelector("#question").innerText = quiz.question;
quizQuestion.querySelector("#a-answer").innerText = quiz.a;
quizQuestion.querySelector("#b-answer").innerText = quiz.b;
quizQuestion.querySelector("#c-answer").innerText = quiz.c;
quizQuestion.querySelector("#d-answer").innerText = quiz.d;
}
difficulty.addEventListener("change",() => {
pickDifficulty();
const filteredQuestions = questions.filter(
(question) => question.difficulty === difficultyLevel);
},true);
function nextQuestion() {
if (questionCounter >= maxQuestion) {
endQuiz();
} else {
increaseQuestionCounter();
const quiztemplate = document.querySelectorAll(".quiz");
const quizparent = quiztemplate[0].parentNode;
quiztemplate.forEach((qq) => quizparent.removeChild(qq));
const quizquestion = quizparent.appendChild(quiztemplate[0].cloneNode(true));
const filteredQuestions = questions.filter(
(question) => question.difficulty === difficultyLevel);
const randomQuestion = Math.floor(Math.random() * filteredQuestions.length);
displayQuestion(quizquestion, filteredQuestions[randomQuestion]);
}
<div id="difficulty" class="center">
<div>
<input type="radio" name="difficulty" id="easy-diff" value="easy">
<label for="easy-diff">Easy</label>
</div>
<div>
<input type="radio" name="difficulty" id="medium-diff" value="medium">
<label for="medium-diff">Medium</label>
</div>
<div>
<input type="radio" name="difficulty" id="hard-diff" value="hard">
<label for="hard-diff">Hard</label>
</div>
</div>
<div id="question-holder" class="hide">
<div id="question-counter"></div>
<div id="score-counter"></div>
<p id="post"></p>
<div class="quiz">
<p id="question">Question placement</p>
<ul>
<li><label for="a" id="a-answer">possible answer</label><input type="radio" name="answer" id="a" class="answer"></li>
<li><label for="b" id="b-answer">possible answer</label><input type="radio" name="answer" id="b" class="answer"></li>
<li><label for="c" id="c-answer">possible answer</label><input type="radio" name="answer" id="c" class="answer"></li>
<li><label for="d" id="d-answer">possible answer</label><input type="radio" name="answer" id="d" class="answer"></li>
</ul>
</div>
<button id="submit" class="btn">Submit</button>
startButton.addEventListener("click", startQuiz);
submitBtn.addEventListener("click", nextQuestion);
Figured it out just add this to the event listener for my difficulty.
difficulty.addEventListener("change",() => {
pickDifficulty();
const filteredQuestions = questions.filter(
(question) => question.difficulty === difficultyLevel);
const randomQuestion = Math.floor(Math.random() * filteredQuestions.length);
const quiztemplate = document.querySelectorAll(".quiz");
const quizparent = quiztemplate[0].parentNode;
quiztemplate.forEach((qq) => quizparent.removeChild(qq));
let quizQuestion = quizparent.appendChild(
quiztemplate[0].cloneNode(true));
displayQuestion(quizQuestion, filteredQuestions[randomQuestion]);
},true);

How can I convert a state component that has a toggle function to a stateless one in reactjs?

I am trying to convert the following component to a functional one so I could use the react context API?
The JSX code for the component I want to convert
class pizzaModal extends Component {
state = {
selected: "small",
showModal: true,
selectedOrder: null
}
toggleHandler = (size)=> ()=>{
this.setState({
toggle: size
});
}
addToOrders = (p)=>{
this.setState(prevState=>({
selectedOrder: p
}))
}
render (){
let attachedClasses = [styles.ImageContainer]
if(this.state.toggle==='small'){
attachedClasses = [styles.ImageContainer, styles.Small]
}
if(this.state.toggle==="medium"){
attachedClasses = [styles.ImageContainer, styles.Medium]
}
if(this.state.toggle==="large"){
attachedClasses=[styles.ImageContainer, styles.Large]
}
return (
<Aux>
<div className={styles.Pizzamodal}>
<div className={styles.ModalContainer}>
<div className={attachedClasses.join(' ')}>
<img src={this.props.image} alt="pizzapicture"/>
</div>
<div className={styles.DetailsContainer}>
<div>
<div className={styles.TextDetails}>
<h1>{this.props.name}</h1>
<p>{this.props.ingredients}</p>
</div>
<div>
<div className={styles.Form}>
<form className={styles.switchButton}>
<input type="radio" name="pizza" id="small" value="small" onChange={this.toggleHandler("small")}
checked={this.state.toggle==="small"}/>
<label for="small">Small</label>
<input type="radio" name="pizza" id="medium" value="medium" onChange={this.toggleHandler("medium")}
checked={this.state.toggle==="medium"}/>
<label for="medium">Medium</label>
<input type="radio" name="pizza" id="large" value="large" onChange={this.toggleHandler("large")}
checked={this.state.toggle==="large"}/>
<label for="large">Large</label>
</form>
</div>
<div className={styles.orderButton}>
<button onClick={this.props.addToOrders}>Add to basket for ₦{this.props.price}</button>
</div>
</div>
</div>
</div>
<div className={styles.Navbar} onClick={this.props.clicked}>
<div></div>
<div></div>
</div>
</div>
</div>
</Aux>
)
}
}
export default pizzaModal;
This is what I have done
const PizzaModal= (props) => {
const [Selected, setSelected] = useState('small')
const toggleHandler = (size)=>{
setSelected({
toggle: Selected
});
}
/*const [orders, setOrders] = useContext([CartContext]);
const addToOrders=()=>{
const pizza = {name: this.props.name, ingredients: this.props.ingredients, image: this.props.image, price: this.props.price}
setOrders([...orders, pizza])
}*/
let attachedClasses = [styles.ImageContainer]
if(setSelected(Selected==='small')){
attachedClasses = [styles.ImageContainer, styles.Small]
}
if(setSelected(Selected==="medium")){
attachedClasses = [styles.ImageContainer, styles.Medium]
}
if(setSelected(Selected==="large")){
attachedClasses=[styles.ImageContainer, styles.Large]
}
return (
<Aux>
<div className={styles.Pizzamodal}>
<div className={styles.ModalContainer}>
<div className={attachedClasses.join(' ')}>
<img src={props.image} alt="pizzapicture"/>
</div>
<div className={styles.DetailsContainer}>
<div>
<div className={styles.TextDetails}>
<h1>{props.name}</h1>
<p>{props.ingredients}</p>
</div>
<div>
<div className={styles.Form}>
<form className={styles.switchButton}>
<input type="radio" name="pizza" id="small" value="small" onChange={toggleHandler("small")}
checked={setSelected(Selected==='small')}/>
<label for="small">Small</label>
<input type="radio" name="pizza" id="medium" value="medium" onChange={toggleHandler("medium")}
checked={setSelected(Selected==='medium')}/>
<label for="medium">Medium</label>
<input type="radio" name="pizza" id="large" value="large" onChange={toggleHandler("large")}
checked={setSelected(Selected==='large')}/>
<label for="large">Large</label>
</form>
</div>
<div className={styles.orderButton}>
<button >Add to basket for ₦{props.price}</button>
</div>
</div>
</div>
</div>
<div className={styles.Navbar} onClick={props.clicked}>
<div></div>
<div></div>
</div>
</div>
</div>
</Aux>
)
}
export default PizzaModal;
I have no error messages on my IDE or on the webpage but when I click on the button that toggles the modal on I get a blank white screen with no error messages.
couple of mistakes i spotted in your code see if this changes anything
You dont need a seperate toggleHandler function to change value of Selected that is what setSelected is there for.
You gave setSelected an object
setSelected({toggle: Selected});
instead u should give it the value of Selected
setSelected(Selected);
And in all the if statements
if(setSelected(Selected==='small'))
is wrong u just have to check
if(Selected==='small')
4.And finally in OnChange
onChange={toggleHandler("small")}
you can just call setSelected
onChange={() => setSelected("small")}
The useState hook returns the current value of the state variable and a function to change it. In your case with
const [selected, setSelected] = useState('small')
you would use selected anywhere you previously would have used this.state.selected and use setSelected() anywhere you previously would have used this.setState({ selected }). So the first issue in your code is the misuse of the setter function when reading the state value.
When you want to pass a function to a component, you have to make sure you're passing the function and not a call to the function. For example
onChange={toggleHandler("large")}
will immediately get the return value of toggleHandler("large") and try to call that when the value changes. Your definition of toggleHandler doesn't return anything, so when you change your radio buttons, you're actually just trying to call undefined as a function, which of course doesn't work.
Also, the onChange handler of an input passes a synthetic event. You should use that to extract which radio button was pressed.
Try something like this:
const PizzaModal = (props) => {
const [selected, setSelected] = useState('small')
const toggleHandler = (event) => {
setSelected(event.target.value);
}
let attachedClasses = [styles.ImageContainer]
if (selected === 'small')) {
attachedClasses = [styles.ImageContainer, styles.Small]
}
if (selected === "medium")) {
attachedClasses = [styles.ImageContainer, styles.Medium]
}
if (selected === "large")) {
attachedClasses=[styles.ImageContainer, styles.Large]
}
return (
<Aux>
<div className={styles.Pizzamodal}>
<div className={styles.ModalContainer}>
<div className={attachedClasses.join(' ')}>
<img src={props.image} alt="pizzapicture"/>
</div>
<div className={styles.DetailsContainer}>
<div>
<div className={styles.TextDetails}>
<h1>{props.name}</h1>
<p>{props.ingredients}</p>
</div>
<div>
<div className={styles.Form}>
<form className={styles.switchButton}>
<input type="radio" name="pizza" id="small" value="small" onChange={toggleHandler} checked={selected === 'small'}/>
<label for="small">Small</label>
<input type="radio" name="pizza" id="medium" value="medium" onChange={toggleHandler} checked={selected === 'medium'}/>
<label for="medium">Medium</label>
<input type="radio" name="pizza" id="large" value="large" onChange={toggleHandler} checked={selected === 'large'}/>
<label for="large">Large</label>
</form>
</div>
<div className={styles.orderButton}>
<button >Add to basket for ₦{props.price}</button>
</div>
</div>
</div>
</div>
<div className={styles.Navbar} onClick={props.clicked}>
<div></div>
<div></div>
</div>
</div>
</div>
</Aux>
)
}
export default PizzaModal;
For future reference, errors also come through in the browser's Javascript console (usually in the developer tools section). You can check there for errors. My guess is that some combination of trying to call undefined as a function and a render loop due to the setSelected calls is what was causing your issue.

Getting the value of checkbox in Reactjs

I'm trying to render components based on the checkbox selection. My approach was as follows:
class ReportMainCat extends Component {
constructor(props) {
super(props);
this.report_next = this.report_next.bind(this);
};
report_next() {
if(this.refs.sexual.checked) {
return <PostOptionBar/>
}
}
render() {
return (
<div className="text_align_left">
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="sexual"/>
<a>Sexual Content</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="selfharm"/>
<a>Threat or self harm</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="abuse"/>
<a>Abuse or bullying</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="illegal"/>
<a>Illegal substances</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="discrimination"/>
<a>Discrimination</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="copyright"/>
<a>Copyright or spam</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="nopermission"/>
<a>Humiliating, embarassing or posted without permission</a>
</div>
<button className="float_right" onClick={this.report_next}>Next</button>
{this.report_next()}
</div>
)
}
}
I'm checking if the checkbox is checked and rendering the component accordingly, but I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined
How do I fix this? Or is this the best approach to do what I want to do?
It's advised not to use string refs in react components.
https://facebook.github.io/react/docs/refs-and-the-dom.html
So refs must be used in this manner
ref={(input) => { this.textInput = input; }}
So your input tag should be something like this
<input type="checkbox" ref={(input) => { this.sexualInput = input; }} />
And then in report_next() function you can get that value by using.
this.sexualInput.checked
Also do try to avoid using so many refs. Use state as much as possible in react components.
Suggestion As per DOC:
If you worked with React before, you might be familiar with an older
API where the ref attribute is a string, like "textInput", and the DOM
node is accessed as this.refs.textInput. We advise against it because
string refs have some issues, are considered legacy, and are likely to
be removed in one of the future releases. If you're currently using
this.refs.textInput to access refs, we recommend the callback pattern
instead.
Changes:
1. Returning a component on click of button will not do anything, for that you need to define a separate function just for onClick.
2. You need to use some state variable otherwise component will not re-rendered automatically and onclick of button you need to update that state value.
Check this snippet:
class ReportMainCat extends React.Component {
constructor(props) {
super(props);
this.state = {
renderComponent: false
}
this.buttonClick = this.buttonClick.bind(this);
};
report_next(){
if(this.refs.sexual && this.refs.sexual.checked){
return <div> hello </div>
}
}
buttonClick(){
this.setState({
renderComponent: true
})
}
render() {
return (
<div className="text_align_left">
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="sexual"/>
<a>Sexual Content</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="selfharm"/>
<a>Threat or self harm</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="abuse"/>
<a>Abuse or bullying</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="illegal"/>
<a>Illegal substances</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="discrimination"/>
<a>Discrimination</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="copyright"/>
<a>Copyright or spam</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="nopermission"/>
<a>Humiliating,embarassing or posted without permission</a>
</div>
<button className="float_right" onClick={this.buttonClick}>Next</button>
{this.report_next()}
</div>
)
}
}
ReactDOM.render(<ReportMainCat/>, document.getElementById('app'))
<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='app'/>
Use the SyntheticEvent, 'e'. Below is an example:
const element1 = "male";
const element2 = "female";
<input
type="checkbox"
name={element1}
value={element1}
onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
</label>
<input
type="checkbox"
name={element2}
value={element2}
onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
</label>
handleChange = (e) => {
// to find out if it's checked or not; returns true or false
const checked = e.target.checked;
// to get the checked value
const checkedValue = e.target.value;
// to get the checked name
const checkedName = e.target.name;
//then you can do with the value all you want to do with it.
};
class ReportMainCat extends React.Component {
constructor(props) {
super(props);
this.state = {
renderComponent: false
}
this.buttonClick = this.buttonClick.bind(this);
};
report_next(){
if(this.refs.sexual && this.refs.sexual.checked){
return <div> hello </div>
}
}
buttonClick(){
this.setState({
renderComponent: true
})
}
render() {
return (
<div className="text_align_left">
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="sexual"/>
<a>Sexual Content</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="selfharm"/>
<a>Threat or self harm</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="abuse"/>
<a>Abuse or bullying</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="illegal"/>
<a>Illegal substances</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="discrimination"/>
<a>Discrimination</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="copyright"/>
<a>Copyright or spam</a>
</div>
<div className="width_100 margin_bottom10px">
<input type="checkbox" ref="nopermission"/>
<a>Humiliating,embarassing or posted without permission</a>
</div>
<button className="float_right" onClick={this.buttonClick}>Next</button>
{this.report_next()}
</div>
)
}
}
ReactDOM.render(<ReportMainCat/>, document.getElementById('app'))
<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`enter code here`.js"></script>
<div id='app'/>

keeping data in 'this' VS 'state'

I wonder is it okay to keep some UI state as instance variables(this) rather than in react state object. For example making controlled inputs sometimes becomes tedious, wouldn't it be better to keep it like:
import React from 'react';
export default class extends React.Component {
selectedCheckboxes = new Set();
searchInput = '';
radioButton = undefined;
onCheckboxChange = ({target: {value}}) => {
if (this.selectedCheckboxes.has(value)) {
this.selectedCheckboxes.delete(value);
} else {
this.selectedCheckboxes.add(value);
}
};
submit = e => {
e.preventDefault();
const searchInput = this.searchInput;
const checkboxes = [...this.selectedCheckboxes];
const radioButton = this.radioButton;
console.log(searchInput, checkboxes, radioButton);
};
render() {
return (
<form className="Example" onSubmit={this.submit}>
<div className="checkboxes">
<input type="checkbox" value="a" onChange={this.onCheckboxChange}/>
<input type="checkbox" value="b" onChange={this.onCheckboxChange}/>
<input type="checkbox" value="c" onChange={this.onCheckboxChange}/>
</div>
<div className="search">
<input type="text" onChange={e => this.searchInput = e.target.value}/>
</div>
<div className="radio-buttons">
<input type="radio"
name="radio"
value="1"
onChange={e => this.radioButton = e.target.value}/>
<input type="radio"
name="radio"
value="2"
onChange={e => this.radioButton = e.target.value}/>
<input type="radio"
name="radio"
value="3"
onChange={e => this.radioButton = e.target.value}/>
</div>
<button type="submit">submit</button>
</form>
)
}
}
I know downside of this approach is that component is not notified when value of this-variables has changed so component will not update. But on the other side sometimes it is not neccessary (like in my example) and it can boost performance as it dont triger re-render, and avoids reconcilation.
Reference

Creating radio button in React using ref

Need to create radio buttons for Title (Mr. & Ms.) using react and the ref attribute.
Code for Class(Omitting the useless part):-
getTitle () {
// how could I get the selected title value here
var title = this.refs. ??;
},
render () {
return (
<div className='input-wrap'>
<label className='label'>
Mr.
</label>
<input className='input'
type='radio'
ref= 'title'
name='user_title'
value='Mr.'
selected />
<label className='label'>
Ms.
</label>
<input className=input'
type='radio'
ref= 'title'
name='user_title'
value='Ms.' />
</div>
)
}
Question:- How could I get the selected Title value in getTitle() ?
You can do it without refs.
class Radio extends React.Component{
constructor(){
super();
this.state = {
inputValue : ''
}
}
change(e){
const val = e.target.value;
this.setState({
inputValue : val
})
}
render(){
return <div>
<label>MR<input type="radio" name="name" onChange={this.change.bind(this)} value="MR"/></label>
<label>MS<input type="radio" name="name" onChange={this.change.bind(this)} value="MS"/></label>
<br/>
<h2>Value : {this.state.inputValue}</h2>
</div>
}
}
React.render(<Radio/>, document.getElementById('container'))
Fiddle example is here
I hope it will help you !
Thanks!

Categories

Resources