So basically iam new in react and iam trying to create multiple select option using axio get method i have a problem that how can i add multiple select option in this file iam trying to do this with check box code below but keep getting error that a string is called on change function. Other than that the checkboxes are not opening due to that function
List item
import React, { Component, Fragment } from "react";
import axios from "axios";
class Home extends Component {
state = {
users: []
};
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/users").then(res => {
console.log(res);
this.setState({
users: res.data
});
});
}
showCheckboxes = () => {
let expanded = false;
const checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
};
onChangeValue = e => {
const value = e.target.value;
debugger;
};
render() {
const { users } = this.state;
const nameList = users.length ? (
<select className="custom-select">
{users.map((user, i) => {
return (
<option key={i} value={user.name}>
{" "}
{user.name}
</option>
);
})}
</select>
) : (
"No Data"
);
const usernameList = users.length ? (
<select className="custom-select">
{users.map((user, i) => {
return (
<option key={i} value={user.username}>
{user.username}
</option>
);
})}
</select>
) : (
"No Data"
);
const emailList = users.length ? (
<select className="custom-select">
{users.map((user, i) => {
return (
<option key={i} value={user.email}>
{user.email}
</option>
);
})}
</select>
) : (
"No Data"
);
return (
<Fragment>
{nameList}
<hr />
{usernameList}
<hr />
{emailList}
<hr />
<div className="multiselect">
<div className="selectBox">
<select>
<option>Select an option</option>
</select>
<div className="overSelect" onClick="showCheckboxes()"></div>
</div>
<div id="checkboxes">
<label htmlFor="one">
<input type="checkbox" id="one" />
First checkbox
</label>
<label htmlFor="two">
<input type="checkbox" id="two" />
Second checkbox
</label>
<label htmlFor="three">
<input type="checkbox" id="three" />
Third checkbox
</label>
</div>
</div>
</Fragment>
);
}
}
export default Home;
this line :
<div className="overSelect" onClick="showCheckboxes()"></div>
to
<div className="overSelect" onClick={this.showCheckboxes}></div>
Related
In my app I am adding new product. But after I click second time it appears on a list. In AddProducts I console.log the array with changed list and it had been updated. But in mu ProductList it doesnt work after click Add so I apply componentDidUpdate to react on changes. Also I use useEffect in App to react on changes sending from AddProduct but it works only I click second times.
AddProduct
function AddProducts(props) {
const [newProduct, setNewProduct] = useState({
productName: ``,
category: ``,
groceries: false,
});
const [newList, setNewList] = useState(props.productsToDisplay);
function handleChange(event) {
event.preventDefault();
setNewProduct({
...newProduct,
[event.target.name]:
event.target.type === "checkbox"
? event.target.checked
: event.target.value,
});
}
function handleAddNewProduct() {
const addProduct = newList.concat([
{
nazwa: newProduct.productName,
kategoria: newProduct.category,
produktSpozywczy: newProduct.groceries,
},
]);
setNewList(addProduct);
props.sendNewProductsToParent(newList);
}
return (
<div className={styles.Wrapper}>
{console.log(newList)}
<p>Add products</p>
<input
name="productName"
value={newProduct.productName}
onChange={handleChange}
></input>
<input
name="category"
value={newProduct.category}
onChange={handleChange}
></input>
<input
name="groceries"
type="checkbox"
value={newProduct.groceries}
onChange={handleChange}
></input>
<p>Is it groceries?</p>
<button onClick={handleAddNewProduct}>Add new product</button>
</div>
);
}
ProductList
class ProductsList extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={commonColumnsStyles.App}>
{console.log(this.props.productsToDisplay)}
<header className={commonColumnsStyles.AppHeader}>
<p>Products list</p>
<ul>
{this.props.productsToDisplay.map((currProduct, index) => (
<li key={index} onClick={() => this.addProduct(index)}>
{currProduct.nazwa}
</li>
))}
</ul>
</header>
</div>
);
}
}
function App() {
const [resultToDisplay, setResultToDisplay] = useState(``);
const [newProductsList, setNewProductsList] = useState(produkty);
return (
<div className={styles.appWrapper}>
{console.log(newProductsList)}
<AddProducts
productsToDisplay={produkty}
sendNewProductsToParent={setNewProductsList}
/>
<div className={styles.columnsWrapper}>
<ProductsList
productsToDisplay={newProductsList}
sendAddedProductsToParent={setResultToDisplay}
/>
</div>
</div>
);
}
Solution for community:
AddProduct
function AddProducts(props) {
const [newProduct, setNewProduct] = useState({
productName: ``,
category: ``,
groceries: false,
});
function handleChange(event) {
event.preventDefault();
setNewProduct({
...newProduct,
[event.target.name]:
event.target.type === "checkbox"
? event.target.checked
: event.target.value,
});
}
function handleAddNewProduct() {
const addProduct = {
nazwa: newProduct.productName,
kategoria: newProduct.category,
produktSpozywczy: newProduct.groceries,
};
props.sendNewProductToParent((listOfPrimiaryProducts) => [
...listOfPrimiaryProducts,
addProduct,
]);
}
return (
<div className={styles.Wrapper}>
<p>Add products</p>
<input
name="productName"
value={newProduct.productName}
onChange={handleChange}
></input>
<input
name="category"
value={newProduct.category}
onChange={handleChange}
></input>
<input
name="groceries"
type="checkbox"
value={newProduct.groceries}
onChange={handleChange}
></input>
<p>Is it groceries?</p>
<button onClick={handleAddNewProduct}>Add new product</button>
</div>
);
}
export default AddProducts;
ProductList
class ProductsList extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={commonColumnsStyles.App}>
<header className={commonColumnsStyles.AppHeader}>
<p>Products list</p>
<ul>
{this.props.productsInShop.map((currProduct, index) => (
<li key={index} onClick={() => this.addProduct(index)}>
{currProduct.nazwa}
</li>
))}
</ul>
</header>
</div>
);
}
}
export default ProductsList;
App
function App() {
const [productsList, setProductsList] = useState(produkty);
return (
<div className={styles.appWrapper}>
<AddProducts sendNewProductToParent={setProductsList} />
<div className={styles.columnsWrapper}>
<ProductsList
productsInShop={productsList}
/>
</div>
</div>
);
}
export default App;
I have a form on a page that includes a dropdown, I want the background color for each div to be different depending on the dropdown selection. For instance, if the user selects Seedy Fruit, I want the list div to be green, and Non Seedy Fruit to be Red.
How can I implement this?
FruitListRender.Jsx
import React, { useState } from "react";
import FruitForm from "./FruitForm";
import FruitList from "./FruitList";
const FruitListRender = () => {
const [newFruit, setNewFruit] = useState("");
const [fruits, setFruitList] = useState([]);
const [fruitType, setFruitType] = useState([]);
return (
<div>
<div>
<FruitForm
newFruit={newFruit}
setNewFruit={setNewFruit}
fruits={fruits}
setFruitList={setFruitList}
/>
</div>
<div>
<FruitList fruits={fruits} setFruitList={setFruitList} />
</div>
</div>
);
};
export default FruitListRender;
FruitListForm
import React from "react";
import { v4 as uuidv4 } from "uuid";
const FruitListForm = ({
newFruit,
setNewFruit,
fruits,
setFruitsList,
}) => {
const addFruits = (event) => {
event.preventDefault();
setFruitList([...fruits, { id: uuidv4(), name: newFruit, type: fruitType }]);
setNewFruits("");
};
return (
<form className="fruitform" onSubmit={addFruits}>
<div>
<input
value={newFruit}
type="text"
placeholder="Name of Fruit"
onChange={(e) => setNewFruit(e.target.value)}
/>
</div>
<div className="fruitform__addfruit">
<select
value={fruitType}
placeholder="Fruit Type"
className="fruitform__dropdown"
onChange={(e) => setFruitType(e.target.value)}
>
<option value="" disabled selected>
Fruit Type
</option>
<option value="Seedy Fruit">Seedy Fruit</option> {" "}
<option value="Non Seedy Fruit">Non Seedy Fruit</option>
</select>
</div>
<div>
<button>Submit</button>
</div>
</form>
);
};
export default FruitListForm;
FruitList.jsx
import React from "react";
const FruitList = ({ fruits = [], setFruitList }) => {
return (
<div>
{fruits.map((fruit) => (
<ul key={fruit.id}>
<li className="fruit-list">
<p>{fruit.name}</p>
<p>{fruit.type}</p>
</li>
</ul>
))}
</div>
);
};
export default FruitList;
Assuming you map the selection to a fruitOption variable, probably by using a hook, then
const optionToClass = {"seedy fruit":"seedy", "non seedy fruit":"non-seedy"}
<li className={"fruit-list "+(optionToClass[fruitOption])}>
and in your CSS file,
.seedy {
background-color: green
}
...
Or you could just do it inline, if you prefer.
I have a problem with the access of the input value, I used here is .map().
Here is the code, <QuestionLabel/>is the children component. projectsData.projectDetail is an available data
//..
{projectsData.projectDetail.questions.map((question) => (
<QuestionLabel
questionTitle={question}
/>
))}
//child component
const QuestionLabel=(props)=>{
const [answerInput, setAnswerInput] = React.useState("");
return(
<div className="contact">
<form className="contact-form" autocomplete="off">
<div class="contact-form-group">
<label
for="name"
class="contact-form-label"
>
{props.questionTitle}
</label>
<input
id="name"
type="text"
class="contact-form-input"
value={answerInput}
onChange={(answer) => setAnswerInput(answer.target.value)}
/>
</div>
</form>
</div>
);
}
export default QuestionLabel;
There are many way to get value from child component for parent component. You can call a function pass from parent to children to set value for parent state when it's changed. Exmaple:
const ParentComponent =(props)=>{
const [valueFromChild, setValueFromChild] = useState('');
return <>
{valueFromChild}
<QuestionLabel questionTitle={'Title'} setValueFromChild={setValueFromChild}/>
</>
}
const QuestionLabel=(props)=>{
const [answerInput, setAnswerInput] = React.useState("")
useEffect(() => {
props.setValueFromChild(answerInput);
}, [answerInput]);
return(
<div className="contact">
<form className="contact-form" autoComplete="off">
<div class="contact-form-group">
<label
for="name"
class="contact-form-label"
>
{props.questionTitle}
</label>
<input
id="name"
type="text"
class="contact-form-input"
value={answerInput}
onChange={(answer) => setAnswerInput(answer.target.value)}
/>
</div>
</form>
</div>
);
}
So you need to have the input state up in the parent.
Since you are mapping through questions array to render the QuestionLabel we can try this...
//..
const ParentComponent = () => {
const [answers, setAnswers] = React.useState({})
useEffect(() => {
projectsData.projectDetail.questions.forEach((_, i) => {
setAnswers(previousAnswers => {...previousAnswers, ["name" + i]: ""})
})
}, [])
const handleAnswers = (e) => {
setAnswers(previousAnswers => {...previousAnswers, [e.target.name]: [e.target.value]})
}
//..
then
//..
{
projectsData.projectDetail.questions.map((question, i) => {
return (
<QuestionLabel questionTitle={question} inputName={"name" + i} answers={answers} handleAnswers={handleAnswers} />
)
})
}
and finally...
//child component
const QuestionLabel=(props)=>{
return(
<div className="contact">
<form className="contact-form" autocomplete="off">
<div class="contact-form-group">
<label
for={props.inputName}
class="contact-form-label"
>
{props.questionTitle}
</label>
<input
id={props.inputName}
name={props.inputName}
type="text"
class="contact-form-input"
value={answers[props.inputName]}
onChange={handleAnswers}
/>
</div>
</form>
</div>
);
}
export default QuestionLabel;
this is how components are look like, i have 3 component that involves in this task, whenever i choose diffrent select dropdown option which is in filter component, change method in parent componet gonna fired and that gonna call another method also in parent component which filterData. its filtering the data but some how after setting state i am not getting filtered data in child component. so i can show filterd data
//parent component
import React, { Component } from 'react';
import ListingsData from '../data/data';
import Listings from '../listings/listings.component';
import Filter from '../filters/filter.component';
import './main_content.styles.scss';
class Main_content extends Component {
constructor(props) {
super();
this.state = {
listingsData: ListingsData,
searchOnChange: '',
filterdProperties: ListingsData,
}
}
change = (e) => {
this.setState({
[e.target.name] : e.target.value
}, () => {
this.filterData();
}
)
}
filterData = () => {
let newData = this.state.listingsData.filter(property => {
return property.type.toLowerCase().toString() === this.state.houseType.toLowerCase().toString()
})
this.setState({ filterdProperties: newData }, () => {
console.log(this.state)
});
}
render() {
return (
<div className='main-content'>
<div className='listings-container'>
<Listings ListingsData={ this.state.filterdProperties } />
</div>
<div className='filter-sidebar'>
<Filter filterTypeHouse={this.change} />
</div>
</div>
);
}
}
export default Main_content;
//child component Listing.component.jsx
import React, {Component} from 'react';
import './listings.styles.scss';
import Listing from '../listing/listing.component'
class Listings extends Component {
constructor(props) {
super(props);
this.state = {
listings: props.ListingsData
}
}
render() {
if (this.state.listings === undefined || this.state.listings.length === 0) {
return <h2>sorry no data found</h2>
}
return (
<div className='listings'>
{this.state.listings.map(({ id, image, address, price, city, rooms, bathrooms, area }) => (
<Listing key={id} image={image} address={address} price={price} city={city} rooms={rooms} bathrooms={bathrooms} area={area} />
))}
</div>
)
}
}
export default Listings;
//child component filter.component.jsx
import React from 'react';
import './filter.styles.scss';
let Filter = (props) => (
<div className='filter'>
<div className='type'>
<label htmlFor='propertyType'>Type</label>
<select className='propertyType' name='houseType' onChange={props.filterTypeHouse} >
<option value='any'>Any</option>
<option value='family-house'>Family House</option>
<option value='single-house'>Single house</option>
<option value='apartment'>Apartment</option>
<option value='villa'>Villa</option>
<option value='office-building'>Office Building</option>
<option value='condo'>Condo</option>
</select>
</div>
<div className='location'>
<label htmlFor='PropertyLocation'>Location</label>
<select className='PropertyLocation'>
<option>Any</option>
<option>New york</option>
<option>California</option>
<option>Washington</option>
<option>philedelphia</option>
<option>Boston</option>
</select>
</div>
<div className='min-price'>
<label htmlFor='priceFrom'>Min-Price</label>
<input type='text' className='priceFrom' placeholder='min-price' />
</div>
<div className='max-price'>
<label htmlFor='priceTo'>Max-Price</label>
<input type='text' className='priceTo' placeholder='max-price' />
</div>
<div className='dealOption'>
<label htmlFor='options'>Type Of Deal</label>
<div className='options'>
<div className='each_option'>
<label htmlFor='any'>Any</label>
<input type='radio' name='dealType' className='any' value='any' />
</div>
<div className='each_option'>
<label htmlFor='sale'>Sale</label>
<input type='radio' name='dealType' className='sale' value='sale' />
</div>
<div className='each_option'>
<label htmlFor='rent'>Rent</label>
<input type='radio' name='dealType' className='rent' value='rent' />
</div>
</div>
</div>
</div>
)
export default Filter;
The component that you use for rendering the filtered lists (Listings) is rendering based on state as per below code.
constructor(props) {
super(props);
this.state = {
listings: props.ListingsData
}
}
The constructor is called only once when the component is mounted. So, the state will never get modified from the initial state, even if you pass new filtered props. To avoid this behaviour, use the props to display the listings data.
So you can change your Listings component to render from props.
class Listings extends React.Component {
render() {
const {ListingData:listings} = this.props;
if (listings === undefined || listings.length === 0) {
return <h2>sorry no data found</h2>
}
return (
<div className='listings'>
{listings.map(({ id, ...props}) => (
<div key={id}>
{JSON.stringify(props)}
</div>
))}
</div>
)
}
}
Try out the below SO snippet. Change the dropdown to apartment, villa, condo to see the filtered data being rendered.
const ListingsData = [
{ type: "apartment", location: "New york" },
{ type: "apartment", location: "New york" },
{ type: "apartment", location: "New york" },
{ type: "villa", location: "New york" },
{ type: "condo", location: "New york" },
{ type: "condo", location: "Washington" }
];
let Filter = props => {
return (
<div className="filter">
<div className="type">
<label htmlFor="propertyType">Type</label>
<select
className="propertyType"
name="houseType"
onChange={props.filterTypeHouse}
>
<option value="any">Any</option>
<option value="family-house">Family House</option>
<option value="single-house">Single house</option>
<option value="apartment">Apartment</option>
<option value="villa">Villa</option>
<option value="office-building">Office Building</option>
<option value="condo">Condo</option>
</select>
</div>
<div className="location">
<label htmlFor="PropertyLocation">Location</label>
<select className="PropertyLocation">
<option>Any</option>
<option>New york</option>
<option>California</option>
<option>Washington</option>
<option>philedelphia</option>
<option>Boston</option>
</select>
</div>
<div className="min-price">
<label htmlFor="priceFrom">Min-Price</label>
<input type="text" className="priceFrom" placeholder="min-price" />
</div>
<div className="max-price">
<label htmlFor="priceTo">Max-Price</label>
<input type="text" className="priceTo" placeholder="max-price" />
</div>
<div className="dealOption">
<label htmlFor="options">Type Of Deal</label>
<div className="options">
<div className="each_option">
<label htmlFor="any">Any</label>
<input type="radio" name="dealType" className="any" value="any" />
</div>
<div className="each_option">
<label htmlFor="sale">Sale</label>
<input type="radio" name="dealType" className="sale" value="sale" />
</div>
<div className="each_option">
<label htmlFor="rent">Rent</label>
<input type="radio" name="dealType" className="rent" value="rent" />
</div>
</div>
</div>
</div>
);
}
class Listings extends React.Component {
render() {
const {ListingData:listings} = this.props;
if (listings === undefined || listings.length === 0) {
return <h2>sorry no data found</h2>
}
return (
<div className='listings'>
{listings.map(({ id, ...props}) => (
<div key={id}>
{JSON.stringify(props)}
</div>
))}
</div>
)
}
}
class Main_content extends React.Component {
constructor(props) {
super();
this.state = {
listingsData: ListingsData,
searchOnChange: '',
filterdProperties: ListingsData,
}
}
change = (e) => {
console.log("Calling change handler");
this.setState({
[e.target.name] : e.target.value
}, () => {
this.filterData();
}
)
}
filterData = () => {
console.log("Calling filter data");
let newData = this.state.listingsData.filter(property => {
return property.type.toLowerCase().toString() === this.state.houseType.toLowerCase().toString()
})
this.setState({ filterdProperties: newData }, () => {
console.log("State", this.state);
});
}
render() {
return (
<div className="main-content">
<div className="listings-container">
<Listings ListingData={this.state.filterdProperties} />
</div>
<div className="filter-sidebar">
<Filter filterTypeHouse={this.change} />
</div>
</div>
);
}
}
ReactDOM.render(<Main_content />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I am trying to set up some functionality on this React component so that a user can add and remove empty radio button options to a page that a user can type text into. The only issue that I am having is that I am relatively new to React and am not 100% how to do this.
import React, { Component } from 'react';
class TextRadio extends Component {
constructor() {
super();
state = {
textValue: ""
}
};
handleInputChange = event => {
const value = event.target.value;
const name = event.target.name;
this.setState({
[name]: value
});
}
addBox = () => {
}
removeBox = () => {
}
render() {
return(
<div>
<div className="form-check">
<input className="form-check-input" type="radio" id="" name="" value="" />
<label className="form-check-label" for="">
<input class="form-control" type="text" placeholder="" />
</label>
</div>
<div className="form-check">
<input className="form-check-input" type="radio" id="option" name="option" value="option" />
<label className="form-check-label" for="option">
<input class="form-control" type="text" placeholder="" />
</label>
</div>
<div className="form-check">
<input className="form-check-input" type="radio" id="option" name="option" value="option" />
<label className="form-check-label" for="option">
<input class="form-control" type="text" placeholder="" />
</label>
</div>
<button type="button" className="btn btn-primary" onClick={this.addBox}>
Add Option
</button>
<button type="button" className="btn btn-danger" onClick={this.removeBox}>
Remove Option
</button>
</div>
);
}
}
export default TextRadio;
The result that I am expecting to happen is to have it so the component can add and remove radio button options from the page depending on the button that the user presses
i was completed just your addBox and RemoveBox functions, i hope that's help you
import React, { Component } from "react";
class TextRadio extends Component {
constructor() {
super();
this.state = {
radioButtons: []
};
}
handleInputChange = event => {
const value = event.target.value;
const name = event.target.name;
};
addBox = () => {
this.setState(prevstate => {
let radioButtons = prevstate.radioButtons;
if (radioButtons.length === 0) {
radioButtons.push({
id: 1,
name: "radiobutton",
value: "test"
});
return {
radioButtons: radioButtons
};
} else {
radioButtons.push({
id: radioButtons[radioButtons.length - 1].id + 1,
name: "raiodButton_" + (radioButtons[radioButtons.length - 1].id + 1),
value: radioButtons[radioButtons.length - 1].value
});
return {
radioButtons: radioButtons
};
}
});
};
removeBox = () => {
this.setState(prevstate => {
let radioButtons = prevstate.radioButtons;
if (radioButtons.length !== 0) {
radioButtons.pop(radioButtons[radioButtons.length - 1]);
return {
radioButtons: radioButtons
};
} else {
return { radioButtons: radioButtons };
}
});
};
render() {
return (
<div>
<div className="form-check">
{this.state.radioButtons.map(radiobutton => {
return (
<div>
<input
className="form-check-input"
type="radio"
id={radiobutton.id}
name={radiobutton.name}
value={radiobutton.value}
/>
<label className="form-check-label" for="">
<input class="form-control" type="text" placeholder="" />
</label>
</div>
);
})}
</div>
<button type="button" className="btn btn-primary" onClick={this.addBox}>
Add Option
</button>
<button
type="button"
className="btn btn-danger"
onClick={this.removeBox}
>
Remove Option
</button>
</div>
);
}
}
export default TextRadio;
https://codesandbox.io/embed/confident-browser-tmojp
I was playing around with your idea and made some changes in the code, just to show you an example, how you can dynamically create new components and store them in applications state and then render out to user based on their actions.
I created new component just for form UI: option, input field and remove button. If user clicks on the Add Option, new item of the component is added to application state and then render out. Remove button is used to remove Item from state.
class TextRadio extends Component {
state = {
optionInputs: []
};
addBox = () => {
const optionInputsUpdated = [
...this.state.optionInputs,
<OptionInput id={uuid.v4()} remove={this.removeBox} />
];
this.setState({ optionInputs: optionInputsUpdated });
};
removeBox = id => {
const optionInputsUpdated = this.state.optionInputs.filter(
item => item.props.id !== id
);
this.setState({ optionInputs: optionInputsUpdated });
};
render() {
return (
<div>
{this.state.optionInputs.map((optionInput, idx) => {
return (
<div key={idx} test="123">
{optionInput}
</div>
);
})}
<button type="button" className="btn btn-primary" onClick={this.addBox}>
Add Option
</button>
</div>
);
}
}
const OptionInput = props => {
return (
<div className="form-check">
<input
className="form-check-input"
type="radio"
id=""
name="radio"
value=""
/>
<label className="form-check-label" for="">
<input className="form-control" type="text" placeholder="" />
</label>{" "}
<button
type="button"
className="btn btn-danger"
onClick={() => props.remove(props.id)}
>
Remove Option
</button>
</div>
);
};
Hope this gives you better understanding, how to achieve your goal.
If you need additional help, just post a comment under this answer, and I will update demo to help you.
Here is DEMO I created from your code: https://codesandbox.io/s/nice-ganguly-s4wls
first you have to initialize an empty array state
this.state={
radioButtons : [{input:''}]
}
then in your return statement you have to loop through the radioButtons array and show the radio button with input
{
this.state.radioButtons.map(item => (
<div className="form-check">
<input className="form-check-input" type="radio" id="option" name="option" value="option" />
<label className="form-check-label" for="option">
<input class="form-control" type="text" placeholder="" />
</label>
</div>
))
}
then in your addBox function append an object on every click
addBox = () => {
this.setState({radioButtons:[...this.state.radioButtons, {input:''}]})
}
function to remove a radio button object
removeBox = () => {
let radioArray = this.state.radioButtons
radioArray.pop()
this.setState({radioButtons:radioArray})
}
Final code Looks like this :
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component{
constructor(props){
super(props);
this.state={
radioButtons :[{input:''}]
}
}
addBox = () => {
this.setState({radioButtons:[...this.state.radioButtons, {input:''}]})
}
removeBox = () => {
let radioArray = this.state.radioButtons
radioArray.pop()
this.setState({radioButtons:radioArray})
}
render(){
return(
<div>
{
this.state.radioButtons.map(item => (
<div className="form-check">
<input className="form-check-input" type="radio" id="option" name="option" value="option" />
<label className="form-check-label" for="option">
<input class="form-control" type="text" placeholder="" />
</label>
</div>
))
}
<button type="button" className="btn btn-primary" onClick={this.addBox}>
Add Option
</button>
<button type="button" className="btn btn-danger" onClick={this.removeBox}>
Remove Option
</button>
</div>
)
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
codepen Example