Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access props inside quotes in React JSX

In JSX, how do you reference a value from props from inside a quoted attribute value?

For example:

<img className="image" src="images/{this.props.image}" /> 

The resulting HTML output is:

<img class="image" src="images/{this.props.image}"> 
like image 626
cantera Avatar asked Feb 10 '14 02:02

cantera


People also ask

Can we directly access props inside your JSX?

Following approaches are there to access props inside quotes in React JSX: Approach 1: We can put any JS expression inside curly braces as the entire attribute value. Approach 2: We can use ES6 template literals.

Can props pass JSX?

Not only can JSX elements be passed as props to components, but we can also pass other components as props.

Why do we use props inside our JSX?

“Props” is a special keyword in React, which stands for properties and is being used for passing data from one component to another. Furthermore, props data is read-only, which means that data coming from the parent should not be changed by child components.


1 Answers

React (or JSX) doesn't support variable interpolation inside an attribute value, but you can put any JS expression inside curly braces as the entire attribute value, so this works:

<img className="image" src={"images/" + this.props.image} /> 
like image 174
Sophie Alpert Avatar answered Oct 05 '22 14:10

Sophie Alpert