Ad

Reactjs Insert Specific Row To Top Of Table

- 1 answer

I have an HTML table which I would like to create a function that takes a row with a specific id, and moves it to the top of the table. I'm not even sure where to begin, but here is the code I am using:

function App() {

  function changeRow(id){
    //Move row with "id" to top of table
  }

  return (
    <div className="App">
      <table>
        <tbody>
          <tr id='row1'>
            <td><b>Value 1</b></td>
            <td>Description 1</td>
            <td><button onClick={()=>changeRow('row1')}>Change Row</button></td>
          </tr>
          <tr id='row2'>
            <td><b>Value 2</b></td>
            <td>Description 2</td>
            <td><button onClick={()=>changeRow('row2')}>Change Row</button></td>
          </tr>
          <tr id='row3'>
            <td><b>Value 3</b></td>
            <td>Description 3</td>
            <td><button onClick={()=>changeRow('row3')}>Change Row</button></td>
          </tr>
          <tr id='row4'>
            <td><b>Value 4</b></td>
            <td>Description 4</td>
            <td><button onClick={()=>changeRow('row4')}>Change Row</button></td>
          </tr>
        </tbody>
      </table>

    </div>
  );
}

And here is the code sandbox:

https://codesandbox.io/s/thirsty-leftpad-vvrmz

Thanks!!

Ad

Answer

Avoid hardcoding data - store it in e.g. array of objects, it will be much easier to tweak on it.

Then - apply state with activeId field. Then sort your array and render it.

https://codesandbox.io/s/polished-resonance-oo063

class App extends React.Component {
  state = {
    activeRowId: null
  };
  changeRow = id => {
    this.setState({ activeRowId: id });
  };

  render() {
    const arr = [
      { id: "row1", value: "value1" },
      { id: "row2", value: "value2" },
      { id: "row3", value: "value3" },
      { id: "row4", value: "value4" }
    ];
    const elements = arr
      .sort(
        (a, b) =>
          +(this.state.activeRowId === b.id) -
          +(this.state.activeRowId === a.id)
      )
      .map(elem => (
        <tr id="row1">
          <td>
            <b>{elem.value}</b>
          </td>
          <td>{elem.value}</td>
          <td>
            <button onClick={() => this.changeRow(elem.id)}>Change Row</button>
          </td>
        </tr>
      ));
    return (
      <div className="App">
        <table>
          <tbody>{elements}</tbody>
        </table>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />

Ad
source: stackoverflow.com
Ad