user15030566
user15030566

Reputation:

How to change value of a button Typescript / React

I have a button with which I handle my language switcher, it is set up to handle cookie, url changes and now I need to make it to change my translations on page as well. The <img> tag is used for changing the country flag.

                    <button
                        onClick={() => {
                        const locale =
                           router.locale === 'en-us'? 'da-dk': 'en-us';
                            setCookie(locale);
                            {handleOnclick;}
                     router.push(/${locale}`,
                                `/${locale}`,
                                {
                                 locale: false,
                                }); }} >
                        {router.locale === 'en-us' ? (
                            <img src={
                                    menuItems.data.body[5].items[0].image
                                        .url}/> ) : (
                            <img
                                src={
                                    menuItems.data.body[4].items[0].image
                                        .url
                                }/>)}
                    </button>

The function of switching between languages handleOnClick is working just fine (tested) This is an example:

<button value="da" onClick={handleOnclick}>
    Danish
</button>
<button value="en" onClick={handleOnclick}>
    English
</button>

But now I need to change the value onClick, since I am having only one button instead of 2, but I don't know how to exactly do it

Upvotes: 0

Views: 1092

Answers (1)

Amir Gorji
Amir Gorji

Reputation: 3335

You can declare a state and switch its value based on the previous value it had.

const [language, setLanguage] = useState('en');

// if your project is written in typescript you can use below line of code
// const [language, setLanguage] = useState<'en' | 'da'>('en');

const handleOnclick = () => {
  setLanguage(prevState => (prevState === 'en' ? 'da' : 'en'));
  // it can also be written like this
  // setLanguage(language === 'en' ? 'da' : 'en');
  // But the 1st is more robust when the event happens more frequently.
};

Then write the button like this

<button value={language} onClick={handleOnclick}>
  {language === 'en' ? 'English' : 'Danish'}
</button>

Upvotes: 1

Related Questions