REACT

Expressions and Attributes


Expressions and Attributes are fundamental to building React components and creating dynamic and interactive UIs. 


Expressions

Expressions are used to embed dynamic content within JSX (JavaScript XML), a syntax extension that resembles HTML. JSX allows developers to write HTML-like code within JavaScript, which React then transforms into real DOM elements. Expressions in React are enclosed in curly braces {} and can include variables, functions, or any JavaScript code that returns a value
 

Embedding Expressions

In JSX, we can embed any JavaScript expression by wrapping it in curly braces {}. This can include variables, function calls, mathematical operations, and more.

 

Example 

const name = 'John';
const element = <h1>Hello, {name}!</h1>;

Explaination:

The expression {name} will be evaluated, and the resulting value will be embedded within the JSX.
 

Expressions Examples

 

1. Variables:

const name = 'Jane';
const greeting = <p>Hello, {name}!</p>;

 

2. Functions:

function formatName(user) {
 return user.firstName + ' ' + user.lastName;
}
const user = { firstName: 'Harper', lastName: 'Perez' };
const element = <h1>Hello, {formatName(user)}!</h1>;

 

3. Ternary Operators:

const isLoggedIn = true;
const element = <div>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</div>;

 

4. Mathematical Operations:

const num1 = 5;
const num2 = 10;
const element = <div>{num1 + num2}</div>; // 15


JSX Attributes

Attributes are used to pass data to components and define their properties, enhancing their functionality and appearance. These attributes resemble HTML attributes but use camelCase naming conventions, like className instead of class and onClick instead of onclick. They allow we to customize components by passing variables, objects, functions, and more.
 

Differences from HTML Attributes
 

1. CamelCase: HTML attributes are typically in lowercase, but JSX uses camelCase naming convention for attributes.

 

// HTML
<div class="my-class"></div>

 

// JSX
<div className="my-class"></div>

 

2. Boolean Attributes: In HTML, We write boolean attributes like disabled without a value. In JSX, we explicitly set them to true or false.

 

// HTML
<button disabled></button>

 

// JSX
<button disabled={true}></button>


3. JSX Attribute Values: We can pass any valid JavaScript expression as an attribute value.
 


const age = 25;
const element = <div data-age={age}></div>;

 

Common JSX Attributes Examples


Class Name:

const className = 'button-primary';
const element = <button className={className}>Click me</button>;

 

Style:

The style attribute in JSX is an object that allows we to define inline styles.

const divStyle = {
 color: 'blue',
 backgroundColor: 'lightgray',
 padding: '10px'
};

const element = <div style={divStyle}>Styled Div</div>;


Event Handlers:

function handleClick() {
 alert('Button clicked!');
}

const element = <button onClick={handleClick}>Click me</button>;

 

Custom Attributes:

const element = <img src="path/to/image.jpg" alt="Description" />;

 

Combining Expressions and Attributes

Combining expressions and attributes allows for dynamic and flexible React components. Here are a few examples to illustrate this:

 

Example 1: Conditional Rendering

const isLoggedIn = false;
const button = <button>{isLoggedIn ? 'Logout' : 'Login'}</button>;

 

Example 2: Dynamic Attributes

const isPrimary = true;

const button = <button className={isPrimary ? 'btn-primary' : 'btn-secondary'}>
 Click me
</button>;


Example 3: Dynamic Event Handlers

function handleClick(isPrimary) {
 alert(isPrimary ? 'Primary Button' : 'Secondary Button');
}

const isPrimary = true;

const button = (
 <button onClick={() => handleClick(isPrimary)}>
   {isPrimary ? 'Primary' : 'Secondary'}
 </button>
);


Putting It All Together

Let's build a small React component that combines all these concepts.
 

// src/DynamicCard.js
import React from 'react';

class DynamicCard extends React.Component {
 constructor(props) {
   super(props);
   this.state = {
     isLoggedIn: false,
     user: {
       firstName: 'John',
       lastName: 'Doe'
     }
   };
   this.toggleLogin = this.toggleLogin.bind(this);
 }

 toggleLogin() {
   this.setState(prevState => ({
     isLoggedIn: !prevState.isLoggedIn
   }));
 }

 render() {
   const { isLoggedIn, user } = this.state;
   const fullName = `${user.firstName} ${user.lastName}`;
   const buttonText = isLoggedIn ? 'Logout' : 'Login';
   const buttonStyle = {
     padding: '10px 20px',
     backgroundColor: isLoggedIn ? 'red' : 'green',
     color: 'white',
     border: 'none',
     borderRadius: '5px'
   };

   return (
     <div style={{ border: '1px solid #ccc', padding: '20px', borderRadius: '10px' }}>
       <h1>{`Hello, ${fullName}`}</h1>
       <p>{isLoggedIn ? 'Welcome back!' : 'Please log in.'}</p>
       <button style={buttonStyle} onClick={this.toggleLogin}>
         {buttonText}
       </button>
     </div>
   );
 }
}

export default DynamicCard;


 

Now, using DynamicCard component in your App.js:
 

// src/App.js
import React from 'react';
import './App.css';
import DynamicCard from './DynamicCard';

function App() {
 return (
   <div className="App">
     <header className="App-header">
       <DynamicCard />
     </header>
   </div>
 );
}

export default App;


Explaination

the DynamicCard component uses JSX expressions and attributes to dynamically render content based on the component's state. The toggleLogin method toggles the isLoggedIn state, and the component re-renders with updated content and styles accordingly. This demonstrates how powerful and flexible JSX expressions and attributes can be in building interactive React applications.