0

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>

2
  • Is it absolutely necessary for you to use cookies? Might be easier to use localStorage instead. Commented Jun 4, 2017 at 11:32
  • If doing that, could you give me some instruction or related article, thank you. Commented Jun 4, 2017 at 12:49

1 Answer 1

3

Alternatively to cookies you could use localStorage. Here's a basic example of that. It sets an item in the storage once the main component is mounted and reacts to that item in the render() method.

componentDidMount() {
  // Get item from localStorage and save it to a constant.
  const hasVisitedBefore = localStorage.getItem('hasVisitedBefore');

  // Check if the user has visited the site (component) before.
  if (!hasVisitedBefore) {
    // If not, set the component state (or dispatch an action if you need)
    // Also set the localStorage so it's globally accessible.
    this.setState({ hasVisitedBefore: false });
    localStorage.setItem('hasVisitedBefore', true);
  }
}

// Based on the state set in `componentDidMount()`, show or hide the welcome modal.
render() {
  return (
    <div>
      {this.state.hasVisitedBefore
        ? 'Welcome back!'
        : 'Welcome for the first time!'}
    </div>
  );
}

Working demo on JSFiddle.

In other components you could then just check for localStorage.getItem('hasVisitedBefore') and render things based on that.

Sign up to request clarification or add additional context in comments.

1 Comment

I am really appreciate for your help, now, I have achieved what I need to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.