I have read this article How can I do to set cookie in the react code? about setting up cookie in reactjs code, however, I cannot use any library, what I can use is just the javascrip. Now, what I want to achieve is to show up a welcome box for the first time visit. What I have done and tested are: 1.the welcome box, it is a component coding in jsx; 2. the cookie coding in js. Both sub-part are tested working, however, when I tried to combine these two part into a single component, it is not working.
var Child = React.createClass({
render: function() {
return (
<div className="container">
<p>Welcome to our website</p>
<button onClick={this.props.onClick}>Click me to close</button>
</div>
);
}
});
var ShowHide = React.createClass({
createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return "";
},
eraseCookie(name) {
createCookie(name,"",-1);
},
firstVisit() {
var isFirstVisit;
var result = readCookie('firstVisit');
if (result == "") {
createCookie('firstVisit', 'true', 365);
isFirstVisit = true;
return isFirstVisit;
}
else {
isFirstVisit = false;
return isFirstVisit;
}
},
getInitialState: function () {
if(firstVisit()) {
return { childVisible: true };
}
else
{
return { childVisible: true };
}
},
onClick: function() {
this.setState({childVisible: !this.state.childVisible});
},
render: function() {
return(
<div>
{
this.state.childVisible
? <Child onClick={this.onClick} />
: null
}
</div>
)
},
});
React.render(<ShowHide />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>