简体   繁体   中英

React.js - add div's on the fly

So I am getting my hands dirty on React and I can't seem to figure out this simple problem (probably because of lack of sleep)

I want to add elements (or divs) inside the render on the fly when I click "Add Row".

How would I go on about it? Do I need to keep it in an array and within the render function, I will have to map it?

class SimpleExample extends React.Component {
    constructor(props) {
        super(props)
        this.handleAddingDivs = this.handleAddingDivs.bind(this)
    }


    handleAddingDivs() {
        const uniqueID = Date.now()
        return (
            <div>
                This is added div! uniqueID: {uniqueID}
            </div>
        )
    }

    render() {
        return (
            <div>
                <h1>These are added divs </h1>

                <button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button>
            </div>
        )
    }
}

Let's say you want to add multiple divs, so maintain a state variable for that, count or any other data (you can use any array also and store the unique value of all the divs), then use map or any other loop to create the divs for that.

Check this working snippet:

 class SimpleExample extends React.Component { constructor(props) { super(props); this.state = {count : 0} this.handleAddingDivs = this.handleAddingDivs.bind(this) } handleAddingDivs() { this.setState({count: this.state.count + 1}) } renderDivs(){ let count = this.state.count, uiItems = []; while(count--) uiItems.push( <div> This is added div! uniqueID: {count} </div> ) return uiItems; } render() { return ( <div> <h1>These are added divs </h1> <button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button> {this.renderDivs()} </div> ) } } ReactDOM.render(<SimpleExample/>, 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'/>

Try the code below. Whenever you click the button, a unique id is generated and stored in state.uids . In render() , added divs are rendered according to state.uids .

 class SimpleExample extends React.Component { constructor(props) { super(props) this.handleAddingDivs = this.handleAddingDivs.bind(this) this.state = {uids:[]} } handleAddingDivs() { let curr = this.state.uids; const uniqueID = Date.now() this.setState({uids:[...curr, uniqueID]}); } render() { return ( <div> <h1>These are added divs </h1> <button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button> { this.state.uids.map((uid, idx)=> <div key={uid}>This is added div! uniqueID: {uid}</div> )} </div> ) } } ReactDOM.render(<SimpleExample/>, 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'/>

yes you will need to store data about new divs somewhere...

this is what flux/redux is sometimes used for: you store all data you need to render in Store and then you know what to render.

But if you whant this using only React, then use state ! Your state should be like this in your case:

{
  addedDivs: [
    {uniqueId: 123},
    {uniqueId: 754},
  ]
}

then in render you will map it (don't forget to add key )

this.state.addedDivs.map((item) = > {return (<div key={item.uniqueId}></div>) })

and onClick you should just add some, using setState:

this.setState((prevState, props) => {
  var addedDivs = prevState.addedDivs;
  var uniqueId = Date.now();
  addedDivs.push({uniqueId: uniqueId});
  return {addedDivs: addedDivs}
});

You are thinking of terms of DOM manipulation/jQuery. When you use React, you need think in terms of data, and how it relates to your DOM.

In your case, you need to:

  • Update your component state with a new row, everytime there is a click to the 'Add Row" button, in the handleAddingDivs() method
  • Render rows based on the state, in the render() method


class SimpleExample extends React.Component {
  constructor(props) {
    super(props)
    this.handleAddingDivs = this.handleAddingDivs.bind(this)
   }

  //Modify state of component when 'Add Row' button is clicked
  handleAddingDivs() {
    const uniqueID = Date.now();
    this.setState({rows: this.state.rows.concat(uniqueId)});
  }

  //The `render()` function will be executed everytime state changes
  render() {
    return (
      <div>
        <h1>These are added divs </h1>
        //The rows are rendered based on the state
        {this.state.rows.map(function(uniqueId) {
          return ( 
            <div key={item.uniqueId}>This is added div! uniqueID: {uniqueID}</div>
          )
        }}
        <button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button>                  
      </div>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM