User1990
User1990

Reputation: 85

Display a React Component as a string

I'm trying to display a helper string text with a react component. The string is part of an array of messages that get displayed on a screen. In this particular string, I'm using an icon for part of the string. The icon is a component. However, I keep getting back [object, object].

What I've tried...

`Click on the ${(<EyeIcon />)} to view the password you have entered.`,

Also just displaying the icon,

<EyeIcon />

I've even tried making the component into a export function.

EyeIcon()

But I can't seem to get it to appear.

Upvotes: 0

Views: 1450

Answers (2)

Tomasz Czechowski
Tomasz Czechowski

Reputation: 641

If this string is part of some conditions try this option:

<>Click on the (<EyeIcon />) to view the password you have entered.</>

Upvotes: 1

windmaomao
windmaomao

Reputation: 7661

Ok, there's some difference between a function, and a function component.

function

  const eyeIcon = s => `Click on ${s}`

This is a function that you can plugin to output a new string based on s.

function component

  const EyeIcon = ({ s }) => <span>Click on {s}</span>

This is a function component that you can use via

  const Title = () => {
    return <EyeIcon s="abc" />
  }

A function component is a function, but it needs to be invoked to produce an element (not a string), therefore the return statement is not a string (Even you output a string there, it'll be wrapped into an element for you).

NOTE:

it's a bit confusing if it's your first time into functional programming, but just watch out for the input and output. The function component input argument is a props object, and it returns a DOM-like element (called React element). There's quite a bit ES6 syntax to confuse you further.

Upvotes: 1

Related Questions