This simply displays an initial string. Then, when a button is clicked, it changes the string.
When run, though, it displays the initial string. Then, when the button is clicked, you can see the string change for a split second. (a log to the console of the new value is also triggered - and works). But, then the old string gets displayed again.
Why would it revert back if the change was made to the state?
Here is the code for displaying the string:
// Display.js
import React from 'react';
class Display extends React.Component {
constructor(props) {
super(props);
this.state = {
blogPosts: "The Bingham Blog"
};
this.clickHandler=this.clickHandler.bind(this);
}
clickHandler() {
this.setState({
blogPosts: "Changed!!!!!!!"
}, () => {console.log(this.state.blogPosts)});
}
render() {
return (
<p>
<form>
<button onClick={this.clickHandler}>Add on</button>
</form>
{this.state.blogPosts}
</p>
);
}
}
export default Display;
Here is the App.js file that calls the <Display />
component:
import React from 'react';
import Display from "./Display";
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Enter text for the blog</h1>
</header>
<div className="display">
<Display />
</div>
</div>
);
}
export default App;
I have been struggling with this for days.
I know it is likely the asynchronous nature of setState
, but I don't know how to fix it.