Conditionally apply CSS classes in React - reactjs

I know this has been answered but I couldn't figure out what is wrong with my code here. I'm trying to add a class based of the conditional field.
React Code:
<div className="boards {task.IsClosed !== 0 ? 'complete' : ''}">
<p>{task.TaskName}</p>
<div>{task.IsClosed !== 0 ? <div>Completed</div> : null}</div>
</div>
Output:
<div class="boards {task.IsClosed !== 0 ? 'complete' : ''}">
<p>Task 2</p>
<div><div>Completed</div></div>
</div>
I want the output to be <div class="boards complete">

<div className=`boards ${task.IsClosed !== 0 ? 'complete' : ''}`>
<p>{task.TaskName}</p>
<div>{task.IsClosed !== 0 ? <div>Completed</div> : null}</div>
</div>
I think you want this^^^
for string interpolation in javascript the ` character must be used for quotes and the expression being interpolated must be within ${}
...
or you can make a variable to store the class i.e.
let className = task.IsClosed !== 0 ? 'complete' : '';
...
...
<div className={className}>
<p>{task.TaskName}</p>
<div>{task.IsClosed !== 0 ? <div>Completed</div> : null}</div>
</div>

Related

How to conditionally add/remove classes with TailwindCSS and React

I have an expression that looks for form errors and appends a div if once bubbles up:
{touched && normalizedError && (
<div className="visible alert-error text-xs text-red-500" role="alert">
{normalizedError}
</div>
)}
I'd like to refactor this and always display the div beneath my input elements but use the invisble class to hide them from the user unless an error is returned—in which case I'd conditional add the visible class.
What's the best way to accomplish this?
There are several ways to accomplish what you want, the easiest would be to add the conditional in the className itself
<div className={`alert-error text-xs text-red-500 ${touched && normalizedError ? 'visible' : 'invisible'}`} role="alert">
{normalizedError}
</div>
There are many different ways of getting this done.
1.Inline inside the class
<div className={`... ${touched && normalizedError ? 'visible' : 'invisible'}`}>
{normalizedError}
</div>
2. Using a variable
let dependentClass = touched && normalizedError ? 'visible' : 'invisible';
className={`... ${dependentClass }`}
3. Using clsx
<div className={clsx('...',`${touched && normalizedError ? 'visible' : 'invisible'}`)}>
{normalizedError}
</div>

React: Checking if an image source / url is empty then return a different url?

<div className="someClass">
<img src={this.getImage(item.image_url)}/>
</div>
Is there a way to check if the source or image_url is empty then if it is, return a different source or image url?
Thanks
try
<div className="someClass">
<img src={item.image_url !== '' ? this.getImage(item.image_url) : 'different url'}/>
</div>
Try this as an improvement of the previous ans.
<div className="someClass">
<img src={item.image_url !== null ? this.getImage(item.image_url) : 'different url'}/>
</div>

How to add event handler to first item in Vue loop?

I have a list of items I am iterating through and need to programmatically add an event handler to the first rendered element. I do not see how this is possible in Vue.
<div ref="componentList" class="component-list col-9">
<template
v-for="( course, index ) in sortedCourseList"
>
<span
v-if="( index > 0 ) && (course.courseTitle[ 0 ] !== sortedCourseList[ index - 1].courseTitle[ 0 ])"
:id="course.courseTitle[ 0 ]"
:key="index"
class="component-list__letter-heading"
>
{{ course.courseTitle[ 0 ] }}
</span>
<CardLong
v-else
:key="index"
:ref="'card' + index"
>>> EVENT HANDLER <<<
:title="{
text: course.courseTitle,
order: 1,
}"
titleTag="h2"
icon
/>
</template>
</div>
I am looking where to implement something like
if ( index === 0 ) { ... }
in the CardLong component instance.
You can use the ternary operator to conditionally call a function on your event, whatever that is:
<div v-for="(a, i) in [1,2,3,4]" :key="i" #click="i == 0 ? doSomething() : ''">
Click Me!
</div>

One output from one array and different output from an array which is nested inside

I have two arrays configuration and sensordata, I want div elements to get displayed when there is a match otherwise another div elements.
//configuration is the first loop
this.props.configuration.forEach((wheel, index) => {
// sensor data is the nested loop
this.props.sensorData.forEach((sensor) => {
if (wheel.wheel) {
//Here I am checking if wheel doesn't exists in sensor
if(wheel.wheel!=sensor.sub_item)
axles.push( //divs to get displayed
<div className='twoaxlewheels' id={axleIndex}>
<span className='infotype' id={wheel.wheel}>9 Bar 16 Pressure</span>
<span className='TyreImage' id={wheel.wheel}><img src={tyre5} /> </span>
</div>)
//If wheel exist in sensor
if (sensor.sub_item == wheel.wheel) {
axles.push( //divs to get displayed
<div className='twoaxlewheels' id={axleIndex}>
<span className='infotype' id={wheel.wheel}>{wheel.wheel == sensor.sub_item ? sensor.temp : ''}</span>
<span className='TyreImage' id={wheel.wheel}>{wheel.wheel == sensor.sub_item ? <img src={tyre5} /> : ''} </span>
</div>)
}
}
})
return axles //returning axles here
})
With above code I am looping multiple times. I couldn't loop it properly.
If I did understand well, your issue is with the conditional rendering ? To display JSX when a condition is true ?
(https://reactjs.org/docs/conditional-rendering.html)
If that's the case, you can do in the return of your function, like :
return (<>
{this.props.sensorData.forEach((sensor) => {
wheel.wheel != sensor.sub_item ? (<div className='twoaxlewheels' id={axleIndex}>
<span className='infotype' id={wheel.wheel}>9 Bar 16 Pressure</span>
<span className='TyreImage' id={wheel.wheel}><img src={tyre5} /> </span>
</div>) : ( <div className='twoaxlewheels' id={axleIndex}>
<span className='infotype' id={wheel.wheel}>{wheel.wheel == sensor.sub_item ? sensor.temp : ''}</span>
<span className='TyreImage' id={wheel.wheel}>{wheel.wheel == sensor.sub_item ? <img src={tyre5} /> : ''} </span>
</div>)</>}

Append (Concatenate) HTML Element To React props Value

I've a JSX like below. The below code is Working (Multiple Ternary Conditionals).
<div className="myClassName">
{this.props.addr? this.props.addr.phoneno : '' }
{this.props.addr? (<span
className='location'>
{this.props.addr.location}
</span>) : ''}
</div>
When I tried with below Syntax with a single Ternary Operator, I'm getting Error.
<div className="myClassName">
{this.props.addr? this.props.addr.phoneno (<span
className='location'>
{this.props.addr.location}
</span>) : '' }
</div>
All I wanted is to append a Span Element with phoneno value. How to do Proper Concatenation here in this Example??
React doesn't allow returning multiple child elements inside a block. So to solve this you can use React.Fragment. There's more explanation about Fragments here.
Below is the corrected syntax.
<div className="myClassName">
{this.props.addr ? (
<React.Fragment>
{this.props.addr.phoneno}
<span className='location'>
{this.props.addr.location}
</span>
</React.Fragment>) : '' }
</div>

Resources