Reputation:
I'm getting trouble while making dynamic new divs. Can anyone help me to do this.
Here is my div.
<div className="intent" id="intent1" style={{border:'1px solid #eee'}}>
<div className="form-group row">
<label htmlFor="intent" className="col-sm-1 col-form-label">Intent</label>
<div className="col-sm-5">
<input type="text" className="form-control" name="indent[]" id="intent1" placeholder="Enter intent"/>
</div>
</div>
</div>
I need to plus/minus the above div dynamically.
Upvotes: 0
Views: 2968
Reputation: 5135
You can manage this through an array
, add items in array
when rows are added and remove them accordingly. You can do the following
class App extends React.Component {
constructor() {
super();
this.state = {
rowList: [true]
};
}
add() {
let rowList = [...this.state.rowList];
rowList.push(true);
this.setState({ rowList });
}
remove(i) {
let rowList = [...this.state.rowList];
rowList.splice(i, 1);
this.setState({ rowList });
}
render() {
let { rowList } = this.state;
return (
<div className="intent" id="intent1" style={{border:'1px solid #eee'}}>
{rowList.map((x, i) => {
return (
<div className="form-group row" key={i}>
<label htmlFor="intent" className="col-sm-1 col-form-label">
Intent
</label>
<div className="col-sm-5">
<input
type="text"
className="form-control"
name="indent[]"
placeholder="Enter intent"
/>
<button onClick={() => this.remove(i)} >Remove</button>
</div>
</div>
)
})}
<button onClick={() => this.add()}>Add New</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<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="root"></div>
Upvotes: 1
Reputation: 1884
Let say you want to add and remove div on the basis of button add and remove. Make two buttons 1. Add Button 2.Remove Button
Make an empty array, in your jsx map the array
Array.map((index,item)=>{
Return <div key={index} > </div>
})
This will create div on the basis of array length.
On click of buttons call a function manageDiv() In manage div check the condition of click (send the parameter of button name so that you can distinguish which button has been clicked) In manageDiv function push object in array if add and splice if remove button clicked.
ManageDiv(type) {
Let Array = this.state.Array
If(type == 'add') {
Array.push({})
}
else
Array.splice(0, 1)
This.setState({
Array
})
}
Upvotes: 0
Reputation: 39
There's not a ton of context here. Are you trying to show/hide or display multiple dynamically?
You can show/hide just by using a plain old js logical AND operator: |jsVariable| && <div/>
You can dynamically display multiple entries of the same div you can do so using the map
function on a js array: |jsArray|.map(item => <div/>)
Upvotes: 0