Sina
Sina

Reputation: 1692

How to truncate a overflowed text in a react element with middle ellipsis?

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)"?

Upvotes: 3

Views: 4703

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

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>

Upvotes: 3

Related Questions