简体   繁体   中英

How to set button default selected in react?

I've a react code (snippet, not a complete code) as shown below which shows list of timezones. On clicking a button, the timezone gets selected and it shows list of all programs.

const timezones = [{label:"PT",timezone:"America/Los_Angeles"},{label:"NT",timezone:"America/St_Johns"}];

const Picker = (props) => {
    console.log(props.selectedTimezone);  // Line Z
    return(
       timezones.map((timezoneObject) => {
           console.log(timezoneObject.timezone);  // Line Y
          return <li><button className={`${timezoneObject.timezone === props.selectedTimezone ? 'selected' : ''}`}
             onClick={(e) => {
             e.preventDefault();
             props.onChange(timezoneObject.timezone);
          }}>{timezoneObject.label}</button></li>
       })
    )
}

What I want achieve is when the page loads then the timezone NT should remain automatically selected without clicking a button. I've added console.log(props) at Line Z and I am getting NT on console but still the class selected is not getting applied for NT timezone . Line Y prints :

America/Los_Angeles
America/St_Johns

React does not store state information between requests. Every time you refresh the page, the state refreshes as well. However, you can use LocalStorage to accomplish this.

Here is a little snippet I found somewhere and adapted for one of the projects I'm working on:

import { useEffect, useState } from 'react';

const useStickyState = (defaultValue, key) => {
  const [value, setValue] = useState(() => {
    const stickyValue = window.localStorage.getItem(key);
    return stickyValue !== null
      ? JSON.parse(stickyValue)
      : defaultValue;
  });

  useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

export default useStickyState;

Then in your component you can use it like this:

...
import useStickyState from '../../app/useStickyState';
...

const YourComponent = () => {
  const [timeZone, setTimeZone] = useStickyState('NT', 'timezone');
  ...
}

The first parameter of useStickyState is the default value and the second parameter is the name of the LocalStorage key to be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM