skip to Main Content

I have a React application and in it a component that displays data in a table. I am interested in displaying some things, including id, but not the whole thing, but only the first 5 characters. I try to display in the following way, and get an error id is not iterable. What can be done to solve this?

const sliceId = (id) => {
  const idCat = [...id].slice(0,5);
  return idCat
}

in return:

clientList.map( (el, i) => (
  <tr key={i} >
    <td style={styleTd}>{ ...sliceId(el._id)}</td>
    { /* ... */ }
  </tr>
))

2

Answers


  1. Chosen as BEST ANSWER

    For me in the end this is the code that worked:

     <td style={styleTd}>{el._id.substring(3,8)}</td>
    

    The problem was that I had an initialState that was a different type and not a String. Thanks to you I solved, thank you.


  2. I am interested in displaying some things, including id, but not the whole thing, but only the first 5 characters.

    The spread syntax (...) is not really necessary here, because as I suppose, the id property is a string.

    I’d suggest you to get rid of it and just use the String#slice function but also secure the possibility that id is undefined using the optional chaining (?).

    const sliceId = (id) => {
      const idCat = id?.slice(0, 5);
      return idCat;
    }
    
    <td style={styleTd}>{sliceId(el._id)}</td>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search