Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptHow to access props inside quotes in React JSX?

How to access props inside quotes in React 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.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

Approach 1: App.js

Javascript




import React, { Component } from "react";
  
class App extends Component {
  render() {
    return (
      <div>
        <img
          alt="React Logo"
  
          // Putting js expression inside curly braces
          src={this.props.image}
        />
      </div>
    );
  }
}
  
export default App;


Approach 2: App.js

Javascript




import React, { Component } from "react";
  
class App extends Component {
  render() {
    return (
      <div>
        <img
          alt="React Logo"
  
          // Using ES6 template literals
          src={`${this.props.image}`} 
        />
      </div>
    );
  }
}
  
export default App;


Note: Make sure to pass the prop value in the <App> component in the index.js file and place any sample picture in the public folder, like here we have used reactLogo.png.

index.js

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
  
ReactDOM.render(
  <React.StrictMode>
    <App image="reactLogo.png" />
  </React.StrictMode>,
  document.getElementById('root')
);


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: You will see the reactLogo.png picture on your browser screen.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments