Home > Net >  How I change states with click btns?
How I change states with click btns?

Time:08-14

I have a file named data.jsx . Here is 3 array inside Products. How can I associate the buttons with these states? For example, when you click on button 1, the 1st state will appear, and when you click on button 2, the 2nd state will appear.

<!-- begin snippet: js hide: false console: true babel: false -->

   **strong text**
import React from 'react'

const App = () => {
  return (
    <>
      <div>App</div>
      <button>Button 1</button>
      <button>Button 2</button>
      <button>Button 3</button>
    </>
  )
}

export default App

import img1 from "./img/img1.jpg";
import img2 from "./img/img2.jpg";
import img3 from "./img/img3.jpg";
import img4 from "./img/img4.jpg";
import img5 from "./img/img5.jpg";
import img6 from "./img/img6.jpg";

const Products = {
    one:[
        {
            id:1,
            img: img1,
        },
        {
            id:2,
            img1: img2,
        },
    ],
    two:[
        {
            id:1,
            img: img3,
        },
        {
            id:2,
            img1: img4,
        },
    ],

    three: [
        {
            id:1,
            img: img5,
        },
        {
            id:2,
            img1: img6,
        },
    ]
};
export default Products;

CodePudding user response:


import React, {useState} from 'react'
import Products from "./product.json"

const App = () => {
    const [state, setState] = useState(0)
    return (
        <>
            <div>App</div>
            <button onClick={() => setState(1)}>Button 1</button>
            <button onClick={() => setState(2)}>Button 2</button>
            <button onClick={() => setState(3)}>Button 3</button>

            {state === 1 ? Products?.one?.map((item, inx) => (<img src={item?.img} alt="" />)) 
              : state === 2 ? Products?.two?.map((item, inx) => (<img src={item?.img} alt="" />)) 
                : state === 3 ? Products?.three?.map((item, inx) => (<img src={item?.img1} alt="" />)) 
                  : null}
        </>
    )
}

export default App
  • Related