0

I am trying to filter through an array so that when a certain tab is clicked, only those results show. I have managed to isolate the certain variables I want to remain but the others that don't fit the criteria still remain. How do I get the filter method to actually render on the page so that the results can be shown. I have searched for hours for and have tried to get the tbody and sort through that but I just get confused as I am mostly new to javascript and react. Can someone point me in the right direction?

Filter Method

const tbody = document.getElementsByTagName('tbody')
    console.log(tbody)
    //change active class
    function addTabBackground() {
        const tabs = document.querySelectorAll('[data-tab]')

        window.onload = function () {
            tabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    if (tab.getAttribute('data-tab') === 'gains') {
                        listOfOptions.map(option => {
                            console.log(option.totalProfit)
                        })
                    }
                    tabs.forEach(tab => {
                        tab.classList.remove('active')
                    })
                    tab.classList.add('active')
                })
            })
        }

    }

<div className="outputs" >
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Stock Name</th>
                            <th>Price Of Option</th>
                            <th>Number Of Options</th>
                            <th>Total Amount Spent</th>
                            <th>Option Sold At</th>
                            <th>Amount Of Options Sold</th>
                            <th>Proft</th>
                        </tr>
                    </thead>
                    {listOfOptions.map(option => {
                        return (
                            <tbody>
                                <tr>
                                    <td>{option.clock}</td>
                                    <td>{option.name.toUpperCase()}</td>
                                    <td>${option.price}</td>
                                    <td>{option.amountOfOptions}</td>
                                    <td>${option.totalAmountSpent.toFixed(2)}</td>
                                    <td>${option.optionPriceSoldAt}</td>
                                    <td>{option.amountOfOptionsSold}</td>
                                    <td style={{ color: option.totalProfit >= 0 ? 'green' : 'red' }}>${option.totalProfit.toFixed(2)}</td>
                                </tr>
                            </tbody>
                        )
                    })}
                </table>
            </div>
4
  • 1
    You're fighting against React here. Instead of mucking with the DOM, just use onClick props, compute your props dynamically in JSX, and conditionally render entire rows based on state. Commented Oct 5, 2020 at 18:55
  • Hi @coreyward, thank you for your answer, but could you explain a little more in depth. How would I go about doing this? Commented Oct 5, 2020 at 19:03
  • Could you clarify how the tabs are rendered? Are they also react components or is this a legacy app with some raw html elements mixed with react components? Commented Oct 5, 2020 at 20:47
  • @AnthonyGarcia-Labiad Hi, they are a react component. They are stored in a component called navbar. Commented Oct 5, 2020 at 21:03

2 Answers 2

3

I have used React-Bootstrap-v5 to get Nav, Nav.Item with eventKey and then passed selectedKey in its onSelect function to change the tabs.

Then once we get the data inside my data variable, I used the map function to go over the array. Inside Map Function I have used the required condition to filter the elements i.e. variable = 'Open' or 'Live'.

This will only show the Open type in Open Tab and Live Type Data inside Live Tab.

Hope it's clear to you.

import React, { useEffect, useState } from 'react';

const TestSeries = () => {
 // Declare Variable for data to be fetched from API
  const [data, setData] = useState([]);

  const fetchTestData = async () => {
    const response = await axios.get(site_ip + '/apiLink');
    setData(response.data.Content);
  };
  useEffect(() => {
    fetchTestData();
  }, []);

  // State Variable to keep track of active tab
  const [activeTab, setActiveTab] = useState('Open');

  return (
    <>
      <Nav
        activeKey={activeTab}
        fill
        variant="pills"
        onSelect={(selectedKey) => {
          setActiveTab(selectedKey);
        }}
      >
        <Nav.Item>
          <Nav.Link eventKey="Open">Open</Nav.Link>
        </Nav.Item>
        <Nav.Item>
          <Nav.Link eventKey="Live">Live</Nav.Link>
        </Nav.Item>
      </Nav>
      <br />

      <Table striped bordered hover>
        <thead>
          <tr>
            <th>#</th>
            <th>Column1</th>
            <th>Column2</th
            <th>Column3</th>
            <th>Column4</th>
            <th>Data Type</th>
          </tr>
        </thead>
        <tbody>
          {data.map((item, index) =>
             // Condition by which data will be filtered 
            item.data_type == activeTab ? ( 
              <tr>
                <td>{index + 1}</td>
                <td>{item.col1}</td>
                <td>{item.col2}</td>
                <td>{item.col3} </td>
                <td>{item.col4}</td>
                <td>{item.data_type}</td>
              </tr>
            ) : null
          )}
        </tbody>
      </Table>
    </>
  );
};

export default TestSeries; 

Result

Open Type Data Live Type Data

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

1 Comment

Please add more clarity to your answer, by explaining what you did, how, so the OP would know how to avoid this mistake next time.
0

Assuming from the comment that you have something vaguely looking like:

function Page() {
  return (
    <>
      <Navbar />
      <Table />
    </>
  )
}

What you need to do is to store the current tab in a state, and pass this state down to the Table component so that you can use a Array.filter when rendering your table.

function Page() {
  const [activeTab, setActiveTab] = useState(DEFAULT_ACTIVE_TAB)
  return (
    <>
      <Navbar activeTab={activeTab} setActiveTab={setActiveTab} />
      <Table activeTab={activeTab} />
    </>
  )
}

Your Navbar component should have a onClick handler where it is calling the setActiveTab function when the active tab change.

Then in your Table component you should have something like this:

function Table({ activeTab }) {
  return (
   <table>
    ...
   {listOfOptions
     .filter(option => /* something depending on the activeTab */)
     .map(option => <... />)
   }
  </table>
}

2 Comments

So, in this function you would use filter and then map through the answer from filter.
Then that will render to the page.

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.