Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JSX how do I set a className as string + {prop}

Tags:

reactjs

I'm a bit new to React and trying to set a className as string + prop. But I'm not sure how to do it and whether that is the best practice.

So what I'm trying to do, and it's obviously not working, is this:

<a data-featherlight='string' + {this.props.data.imageUrl}> 

How would I go about writing this?

like image 950
andromedainiative Avatar asked Feb 02 '16 08:02

andromedainiative


People also ask

How do I pass a className as a prop?

To pass class names as props to a React component:Pass a string containing the class names as a prop. Destructure the prop in the child component. Assign the class names to an element, e.g. <h2 className={className}>Content</h2> .

How do I pass JSX as a prop?

You want to use JSX inside your props You can simply use {} to cause JSX to parse the parameter. The only limitation is the same as for every JSX element: It must return only one root element.


2 Answers

You can use string concatenation

<a data-featherlight={'string' + this.props.data.imageUrl}> 

or use Template strings new ES2015 feature

<a data-featherlight={ `string${this.props.data.imageUrl}` }> 
like image 58
Oleksandr T. Avatar answered Sep 27 '22 20:09

Oleksandr T.


You can also try it:

<a data-featherlight={'string1' + this.props.data.imageUrl + 'string2'}> 

or

<a data-featherlight={ `string1 ${this.props.data.imageUrl} string2` }> 

If you are using Link component then you can concatenation like this:

<Link to={`getting-started/${this.props.message}`}>      <h1>Under {this.props.message}/-</h1> </Link> 
like image 42
Shubham Verma Avatar answered Sep 27 '22 21:09

Shubham Verma