I am trying to build a web app where I am trying to call a function on button click. I am using react-engine as templating engine using JSX pages. Below is my layout.jsx page
import React from 'react';
import Success from "./components/success.jsx";
import ReactDOM from 'react-dom';
class Layout extends React.Component {
constructor(props) {
super(props);
this.displayName = 'Layout';
this.state = {data:[]};
//this.arrayHandler = this.arrayHandler.bind(this);
this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
this.printHandler = this.printHandler.bind(this);
}
/*function submitter(){
//console.log("in submitter function", user.value);
},*/
/*arrayHandler(){
var item = "first item";
var myArray = this.state.data;
myArray.push(item);
this.setState({data:myArray})
}*/
forceUpdateHandler(){
return this.forceUpdate();
}
printHandler(){
return this.displayName = "Sourav";
}
render() {
return (
<html>
<head>
<title>JSX</title>
</head>
<body>
<h1>Welcome to React JSX Page</h1>
<div id = "maincontent">
<Message msg = "Displaying message"/>
<p id = "para"></p>
<Success successMsg = "Transaction successful"/>
<h2>Arrays: {this.props.propArray}</h2>
<h2>Objects: {this.props.propObject.objectName1}</h2>
<input type = "button" onClick = {this.props.propHandler} value = "Add items"/>
<h3>State Arrays: {this.state.data}</h3>
<button onClick = {this.forceUpdateHandler}>FORCE UPDATE</button>
<h4>Random number: {Math.random()}</h4>
<button onClick = {this.printHandler}>Show name</button>
<p>{this.displayName}</p>
</div>
</body>
</html>
);
}
}
Layout.propTypes = {
propArray: React.PropTypes.array.isRequired,
propObject: React.PropTypes.object,
propHandler: React.PropTypes.func
}
Layout.defaultProps = {
propArray: [1,2,3,4,5],
propHandler: function arrayHandler(){
var item = "first item";
var myArray = this.state.data;
myArray.push(item);
this.setState({data:myArray})
},
propObject: {
objectName1:"objectValue1",
objectName2: "objectValue2",
objectName3: "objectValue3"
}
}
class Message extends React.Component{
render(){
return(
<div>
<h2>{this.props.msg}</h2>
</div>
)
}
}
//ReactDOM.render(<Layout/>, );
export default Layout;
i have tried calling the function using both this.props as well as calling directly after binding this to it. However, both the approaches did not work.
Could you please help me with this. I am totally stuck here.
I am assuming you know how to do the react setup thing etc. This is how events are bound and eventually change DOM elements.
Problem in your code is you trying to update a property on component
this.displayName = "Sourav"
and hoping that UI will automatically get updated based on that. But that's not the way React works. To display changes you need to change a component'sstate
orprops
(props are set through parent component). Also you don't writehead
,html
body
tags etc inside react component.