3

I am new to react. so any help is greatly appreciated. I have a react table in which one of the columns holds the name of each row. I have names like "entry", "entry (1)", ... "entry (n)" I want to be able to deal with the text overflow when the name is long but I want to keep the index of the name, hence can't use css (text-overflow:"ellipses"

is there a way that I could have "ent... (n)"?

Sina
  • 1,632
  • 3
  • 15
  • 21
  • Check the width of the `` element (see https://stackoverflow.com/questions/43817118/how-to-get-the-width-of-a-react-element), and if it too long - truncate it, letter by letter in a loop, until it's in the correct width. – Chayim Friedman Jul 26 '18 at 19:00

1 Answers1

3

You can achieve that with a combination of flexbox and position: absolute. The absolute position prevents the div from effecting the width of the table column, while filling the td's full width. The flexbox limits the text area width, which enables the appearance of ellipsis:

const Entry = ({ children, index }) => (
  <div className="entry">
    <div className="entry__inner">
      <span className="entry__text">{children}</span>
      <span className="entry__index">({index})</span>
    </div>
  </div>
);

const Demo = ({ entries }) => (
  <table>
    <thead>
      <th>Name</th>
    </thead>
    <tbody>
      {entries.map((text, index) => (
        <tr key={index}>
          <td>
            <Entry index={index}>{text}</Entry>
          </td>
        </tr>
      ))}
    </tbody>
  </table>
);

const entries = ['entry', 'long entry', 'long long entry'];

ReactDOM.render(
  <Demo entries={entries} />,
  demo
);
td {
  width: 5.5em;
}

.entry {
  position: relative;
  height: 1em;
}

.entry__inner {
  position: absolute;
  display: flex;
  left: 0;
  right: 0;
}

.entry__text {
  flex: 1;
  margin-right: 0.5em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.entry__index {
  text-align: right();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="demo"></div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209