Negin Basiri Negin Basiri - 2 months ago 9
React JSX Question

Constructing string using react property and es6 template feature

I have an easy question. I need to construct the href using the react property and es6 template feature. My code is below however after rendering the subHeader in href is not replaced with its value.

subHeaders = this.props.subHeaders.map((subHeader, i) => {
return <a className="articleSidebar__summaryText" href='#${subHeader}' key={i}>{subHeader}</a>;
});


How can I achieve this?

Answer

You're not using the right syntax in the href part.

Are you trying to get an output like #something? In that case, it should be:

href={`#${subHeader}`}

You need to use template literals (``) when you want to do string interpolation. And you need to use {} around the template literal because thats the syntax you need to use in order to set a prop to some JS expression instead of some literal string.

Comments