Home  >  Q&A  >  body text

"Using React to implement dynamic variables"

<p>I have the following code in React: </p> <pre class="brush:js;toolbar:false;">const TABS = [ { value: "Names", label: "Names", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Logs", label: "Logs", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Groups", label: "Groups", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Subscriptions", label: "Subscriptions", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, ] </pre> <p>I tried to make the code dynamic like this: </p> <pre class="brush:js;toolbar:false;">const values ​​= ["Names","Logs","Groups","Subscriptions"]; const labels = ["Names","Logs","Groups","Subscriptions"]; const TABS = [ { value: {values}, label: {labels}, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }] </pre> <p>Am I right? </p>
P粉008829791P粉008829791435 days ago423

reply all(1)I'll reply

  • P粉904405941

    P粉9044059412023-09-03 13:15:59

    use:

    const values = ["Names", "Logs", "Groups", "Subscriptions"];
    
    const TABS = values.map((e, i) =>
        {
            return {
                value: e,
                label: e,
                onclick: (obj) => {
                    tabOnClick(obj.value);
                },
                selected: mainTabSelected,
            }
        }
    )

    This will map each element on your values ​​array and inject a new object in the Tabs array for each tab.

    reply
    0
  • Cancelreply