javascript - ReactJs, Generating events outside of reactjs app -


while trying out reactjs, facing below design issue:

below simple html trying simulate chat app, building list of online members , trying work out code add new members list.

the below react app consists of following class in dom hierarchy.

chatapp > memberlist > member

in react class chatapp, able use setinterval update members collection , generate new dom new member, want try same outside chatapp class.

so have added button 'add member' , call function on click in turn add new member list.

but, how should instance of react chatapp , setstate method outside of react app?

<html>  <head>      <style>         .onlinelist{             width:300px;             height:500px;             display:inline-block;             overflow:auto;             border:1px solid lightgray;         }          .onlinelist a{             display:inline-block;             width:100%;             padding:10px;             box-sizing:border-box;             text-decoration:none;             color:gray;             font-weight:bold;             border-top:1px solid lightgray;             border-bottom:1px solid lightgray;         }         .onlinelist a:hover{             color:black;             background-color:lightgray;         }      </style>      <script src="js/jquery-1.11.3.min.js"></script>     <script src="js/react-with-addons.js"></script>     <script src="js/jsxtransformer.js"></script>      <script>         function addnewmember(){             // how can setstate in chatapp react class called here?         }     </script>      </head>  <body>     <button onclick="addnewmember()">add new member</button>     <div id="chatapp"></div>     <script type="text/jsx">         var member = react.createclass({             render: function() {                 return <a href='#'>{this.props.memberinfo}</a>;             }         });          var memberlist = react.createclass({             render: function(){                 var membersdom = [];                 for(var m=0; m < this.props.members.length;m++){                     membersdom.push(<member memberinfo={this.props.members[m].name}/>);                 }                 return (                     <div id='onlinelist' classname={'onlinelist'}>{membersdom}</div>                 )             }         });          var chatapp = react.createclass({             getinitialstate: function(){                 var members = {                     members: []                 };                 for(var m=0;m<1;m++){                     members.members.push({name: m + 1});                 };  /*              setinterval(function(){                     members.members.push({name: members.members.length + 1 });                     this.setstate(members);                 }.bind(this),2000); */                 return members;             },             render: function(){                 return (                     <div id='container'>                         <memberlist members={this.state.members}/>                     </div>                 )             }         })          react.render(             <chatapp/>,             document.getelementbyid('chatapp')         );      </script> </body>   </html> 

you're never supposed set component's state outside of component.

a react app should set hierarchy of components, top-level component managing state of children. if want functionality outside of chatapp, need move button parent component, along state want modify , addnewmember handler. pass state chatapp props, memberlist.

that being said, there's no reason why couldn't include button , addnewmember in chatapp:

addnewmember: function (e) {   e.preventdefault();    var name = this.state.members.length + 1;   var members = this.state.members;    this.setstate({     members: members.concat([{name: name}])   }); },   render: function(){    return (     <div>       <button onclick={this.addnewmember}>add new member</button>       <div id='container'>         <memberlist members={this.state.members}/>       </div>     </div>   )  } 

also, isn't directly related question, shouldn't call setstate in getinitialstate. purpose instantiate component's state, since invoked once, before component rendered, , doesn't trigger re-render other lifecycle methods.

so in example, return empty members array. then, if wanted add members setinterval, settimeout, or async process, in componentdidmount. using addnewmember above, (make sure account e if run it):

getinitialstate: function () {   return {     members: []   }; },  componentdidmount: function () {   setinterval(this.addnewmember, 2000); } 

anyway, hope helps. feel free ask me questions. i'd happy go more detail structuring more complex react apps , best practices.


Comments

  1. Hi admin,
    Your coding gives a clear explanation on generating events outside of reactjs app. Keep up the good work and share more like this.
    React js Training in Chennai | React js Training

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Found this content great and sharable with other resources. If you are willing to participate and win grand lottery prizes in KBC, visit https://kbcofficialwinner.com website to get detailed information.

    ReplyDelete

Post a Comment

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -