Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: onClick change element

I've just started learning React and have a question.

I want to do the following:

If a user clicks on a paragraph I want to change the element to an input field that has the contents of the paragraph prefilled. (The end goal is direct editing if the user has certain privileges)

I'm come this far but am totally at a loss.

var AppHeader = React.createClass({     editSlogan : function(){         return (             <input type="text" value={this.props.slogan} onChange={this.saveEdit}/>          )     },     saveEdit : function(){         // ajax to server     },     render: function(){         return (             <header>                 <div className="container-fluid">                     <div className="row">                         <div className="col-md-12">                             <h1>{this.props.name}</h1>                             <p onClick={this.editSlogan}>{this.props.slogan}</p>                         </div>                     </div>                 </div>             </header>         );     } }); 

How can I override the render from the editSlogan function?

like image 455
jansmolders86 Avatar asked Mar 27 '15 14:03

jansmolders86


People also ask

How do I change the onClick component in React?

We have to set initial state value inside constructor function and set click event handler of the element upon which click, results in changing state. Then pass the function to the click handler and change the state of the component inside the function using setState.

How do you change elements in React?

React elements are immutable. Once you create an element, you can't change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.


1 Answers

If I understand your questions correctly, you want to render a different element in case of an "onClick" event.

This is a great use case for react states.

Take the following example

React.createClass({      getInitialState : function() {        return { showMe : false };     },     onClick : function() {        this.setState({ showMe : true} );     },     render : function() {         if(this.state.showMe) {              return (<div> one div </div>);         } else {              return (<a onClick={this.onClick}> press me </a>);         }      } }) 

This will change the components state, and makes React render the div instead of the a-tag. When a components state is altered(using the setState method), React calculates if it needs to rerender itself, and in that case, which parts of the component it needs to rerender.

More about states https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html

like image 119
Silfverstrom Avatar answered Sep 19 '22 16:09

Silfverstrom