Reputation: 77
I have read the method about how to show/hide a component and I made some modification to it, however, my modification is not working.enter link description here
My Not working code is here:
var Child = React.createClass({
render: function() {
return (
<div className="container">
<p>Welcome to our website</p>
<button onClick={this.onClick}>Click me to close</button>
</div>
);
}
});
var ShowHide = React.createClass({
getInitialState: function () {
return { childVisible: ture };
},
render: function() {
return(
<div>
{
this.state.childVisible
? <Child />
: null
}
</div>
)
},
onClick: function() {
this.setState({childVisible: !this.state.childVisible});
}
});
React.render(<ShowHide />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
I have two goals: 1. The first goal is to add a button to close this welcome box. 2. The second goal is to add a cookie to it, in order to show this welcome box to user when they visit this website for the first time, and once they click to close it, it will not show up again if not clear the cookie.
Upvotes: 0
Views: 775
Reputation: 419
You have to pass the onClick function as a prop from ShowHide
to Child
.
<Child onClick={this.onClick} />
Then your button in Child
would look like this
<button onClick={this.props.onClick}>...</button>
You also have a little typo in your initialState, you wrote ture
instead of true
.
Upvotes: 1
Reputation: 49
As an additional tip, I'd recommend you to use ES6 classes instead of React's createClass. Better performance and more standard :D
Upvotes: 0