0

I've got a banner component that has a message field - in this case a welcome message.

One of the props is called 'headline', in which you can enter your message. Currently I'm using the message 'Hi Joe, welcome to your account', but I'd like to pull the name from another prop.

This is what I currently have in the ReactDOM.render:

ReactDOM.render(React.createElement(PriorityComponents.HeaderBanner, {
      desktopImage:{},
      mobImage:{},
      altText:'alt test goes here',
      isLeftAligned:true,
      userName: 'Joe',
      headline: 'Hi Joe, welcome to your account',
      label: ''
    }), document.getElementById("HeaderBanner"));

The headline is being called in as follows:

<Editable tag="h1" className="headerBanner__body__headline" html={article.headline} />

I thought I might be able to use the following:
userName: 'Joe', headline: 'Hi ' + userName + ', welcome to your account'

This seems to be breaking the component! Any idea how to reference the username in the headline prop?

  • please provide a code sample. also please share what you've tried to do. – falinsky Jun 27 '18 at 08:05
  • Please provide a more complete example. It doesn't seem like you are using JSX. I believe it might even be a duplicate of [Self-references in object literal declarations](https://stackoverflow.com/q/4616202/218196), but at the moment it's unclear what the context of your code example is. – Felix Kling Jun 27 '18 at 08:06
  • I've updated with a bit more detail – Jonny Vaine Jun 27 '18 at 08:35

2 Answers2

0

Why not just using an placeholder which will be replaced when rendering:

userName: 'Joe',
headline: 'Hi {userName}, welcome to your account'

in render()

return <div>
  <div className="headline">
      {this.props.headline.replace('{userName}', this.props.userName)}
  </div>
</div>;
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
0

You should be able to use ES6 Template literals like this:

const username = 'Joe';

// While sending props
username: {username} 
headline: {`Hi ${username}, welcome to your account`} 

Support for es6 object shorthand in react still wip so you can't use it for username just yet.

Anu
  • 1,079
  • 8
  • 12