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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With