0

I have an array of span elements that I need to render inside another static text.

Example final result: Put 3, 1 and 2 in the right order here the bold numbers are the spans

Here is my code

generateQuestion() {
    const newState = { ...this.state };
    let numbers= newState.numbers.map((item, index) => <span style={{color: "red"}}>{item.number}</span>)
    let textQuestion = `Place the numbers ${numbers[0]}, ${numbers[1]} and ${numbers[2]} in the right order.`;

    return (
        <div>{textQuestion}</div>
    );
}

The problem is I'm getting this at render time Place the numbers [object Object], [object Object] and [object Object] in the right order

When I render numbers array directly I am getting the spans

return (
        <div>{numbers}</div>
);

How can I solve this issue?

2
  • Use a react fragment and not a template string? Or just put the text into the return? Commented Nov 23, 2021 at 13:49
  • Can you please write the solution ? Commented Nov 23, 2021 at 13:50

1 Answer 1

1

You are trying to render objects inside string, the right way is to use jsx instead of string:

generateQuestion() {
  const newState = { ...this.state };
  let numbers= newState.numbers.map((item, index) => <span style={{color: "red"}}>{item.number}</span>)
  let textQuestion = <div>Place the numbers {numbers[0]}, {numbers[1]} and {numbers[2]} in the right order.<div>;

  return (
      {textQuestion}
  );
}
Sign up to request clarification or add additional context in comments.

4 Comments

The variable textQuestion is unnecessary.
It works thank you , I don't know how I missed that.
@evolutionxbox yes it's just to make it more clear compared to using string
@Amine Glad it helped! Please, consider accepting the answer.

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.