1

I have a following code. This is the rest of the react class component that shall be rendered.

 render() {
        return (
          <div>
            {this.state.todos.map((todo) => (
              <h1 id={todo.id} onClick={this.deleteTodo}> {todo.name} </h1>
            ))}
          </div>
        );
      }

I would like to have assigned id={todo.id} as number and not as text. Don't you know please, how to fix it?

Right now, it is actually like this: id="1", but I would need that as id=1.

Thank you for your help

2 Answers 2

1

It's very simple. Provided that the ID always comes as a number, then you can use the parseInt() function directly. It parses a string and returns an integer. So now it looks like this:

render() {
    return (
      <div>
        {this.state.todos.map((todo) => (
          <h1 id={parseInt(todo.id)} onClick={this.deleteTodo}>
            {todo.name} 
          </h1>
        ))}
      </div>
    );
  }
Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad to hear that. If it answers your question, don't forget to mark it as an answer. Thanks :)
1

Use Number, the constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.

  <h1 id={Number(todo.id)} onClick={this.deleteTodo}> {todo.name} </h1>

Other option:

  <h1 id={+todo.id} onClick={this.deleteTodo}> {todo.name} </h1>

1 Comment

Thank you, both approaches are working perfect for me.

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.