Conditionally render a badge for active/inactive User - javascript

I am trying to render conditionally a badge, based on the logged condition of a user. If the props coming from the server is true, then the badge is green, else grey.
I have tried various solutions, from basic if/else in the JSX, to classNames but the badge isn't being render.
My Code:
{user.loggedIn ? (
<div
className={classNames('badge badge-pill', {
'badge-success': user.loggedIn,
'badge-danger': !user.loggedIn
})}
/>
I don't see anything wrong with the code. I mean the item should have rendered, with multiple solutions. Any ideas, what I am doing wrong.
<span
className={
user.loggedIn ? 'badge badge-pill badge-success' : 'badge badge-pill badge-muted'
}
/>
I have tried this as well.
I can see the element in the React-Dev-Tools, being render correctly, witht the right prop, but I cannot see it render in the screen.

Your contents will only get rendered if user is loggedIn. Also the div tag must be closed inside the condition { isLoggedIn }
you should try something like this:
{user.loggedIn ? (
<div className={'badge badge-pill badge-success'}>ENTER YOUR CONTENT HERE</div>) : (
<div className={'badge badge-pill badge-danger'}>ENTER YOUR CONTENT HERE</div>
)}
but since the div is self-closing and has no contents, it doesn't display it, so add some content too

The badge for logged out user will never be displayed as you put a rendering condition around all the div with user.loggedInd ? (yourComponent...)

If user.loggedIn is boolean, then you can just write
<div
className={
classNames('badge badge-pill', {
'badge-success': user.loggedIn,
'badge-danger': user.loggedIn
})
}
/>

I think it's better to avoid conditional in jsx directly. You can do something like this:
let attachClass = ['badge', 'badge-pill']
if(user.loggedIn){
attachClass = [...attachClass, 'badge-success'].join(' ');
}else{
attachClass = [...attachClass, 'badge-danger'].join(' ');
}
Than you can just return one div with className attach class:
<div className={attachClass}></div>

The issue look into the user.loggedIn is not defined or return false
const loggedIn = true;
<span className={loggedIn ? 'badge-success' : 'badge-muted'}>
Css Change </span>
Codepen

Related

No items being rendered when the page reloads - trying to implement a search bar

I am trying to implement a search bar and I am going to attach the code for it below. The issue is that when the page reloads and the search bar is empty, no products end up getting render but as soon I start typing something in the search bar, the items start to render as per the search key.
Can anyone assist me with this please?
.filter((val) => {
if (props.searchTerm == "") {
return val;
} else if (
val.additionalInfo.toLowerCase().includes(props.searchTerm)
) {
return val;
}
})
.map((post) => {
return (
<div className="product-metainfo col-2 mb-4">
<img src={post.images[0].src}></img>
<h3 className="product-brand">{post.brand}</h3>
<h4 className="product-product">{post.additionalInfo}</h4>
<div className="product-price">
<span>
<span className="discounted-price">Rs. {post.price} </span>
<span className="product-strike"> Rs. {post.mrp}</span>
</span>
<span className="product-discountPercentage">
({Math.floor((100 * post.discount) / post.mrp)}% off)
</span>
</div>
</div>
);
})}
Did you set the default state for searchTerm as undefined or null? In this case you need to set the default state for searchTerm as empty string to make it work.

Conditional V-HTML rendering

Just wondering if there is something I'm missing here:
<span v-html="(shouldParseHTMLBool ? HTMLContent : '')">
{{ contentWithoutParsedHTML }}
</span>
doens't appear to work.
I would like to have this span interpreting HTML only if shouldParseHTMLBool is set to true.
Is it something possible, or should I use a v-if? In this trivial example it's not a big deal, but with my components I'll have to duplicate ~30 lines for each condition.
It's better to make if condition away from template as much as possible.
You should create a computed object instead.
[template]
<span v-html="computedContent"></span>
[script]
...
computed: {
computedContent: function () {
return this.shouldParseHTMLBool ? this.HTMLContent : ''
}
},
...
The v-html directive replaces the innerHTML of the element. In your case, the {{ contentWithoutParsedHTML }} will be replaced with the value of (shouldParseHTMLBool ? HTMLContent : '')
You can do something like
<template>
<span v-html="conditionalParse"></span>
</template>
<script>
methods: {
conditionalParse: function () {
return this.shouldParseHTMLBool ? this.HTMLContent : ''
}
</script>
try this
<span v-if="shouldParseHTMLBool" v-html="HTMLContentForIfCondition" >All</span>
<span v-else v-html="HTMLContentForElseCondition" ></span>
You can use two spans, One for v-if is true and other for v-else

React inline logic in render()

I just wonder how apply inline templates logic in React.
I mean in case when I need change class of element how to do that easily?
class RegisterForm extends Component {
...
render() {
let email = this.state.email.error; //true or false
return (<div {email ? className="has-error" : className="regular"}></div>)
}
Then I have an error:
Syntax error: C:/project/components/signup/index.js: Unexpected token, expected ... (107:22)
How to perform that?
Or it's only possible to wrap in if/else full div block only?
You could do a couple things:
<div className={email ? "has-error" : "regular"}> </div>
Or to keep it cleaner
let email = this.state.email.error;
let divClass = email ? "has-error" : "regular";
return <div className={divClass}> </div>
Assign the value conditionally not attribute. Define className attribute and assign its value on the basis of email value.
Write it like this:
<div className = { email ? "has-error" : "regular"}> </div>

React - Optionally wrap an item in a link

I have a React component that displays a title and some text. I want to optionally wrap the title in a link (the same component is used in more than one place), and would appreciate guidance for the best way to do it.
My component looks like this:
var FeedItem = React.createClass({
renderRawMarkup: function(text) { ... },
render: function() {
var item = this.props.item,
rawBody = this.renderRawMarkup(item.body);
return (
<article className="feed-item">
<h2 className="feed-item__title">{item.title{</h2>
<div className="feed-item__body" dangerouslySetInnerHTML={rawBody} >
</div>
</article>
);
});
Am I best to create a new component just for the title? Or can I use an if inside the return, e.g.:
<h2 className="feed-item__title">
{if (item.path) { <a href={item.path}> }}
{item.title}
{if (item.path) { </a> }}
</h2>
I'm a bit of a React novice so apologies if I'm approaching the problem from completely the wrong angle!
You can't use if statements inside jsx, but you can make use of ternary expressions. In your case, you can use:
<h2 className="feed-item__title">
{ item.path ? <a href={item.path}>{item.title}</a> : {item.title} }
</h2>
This is stated in the official documentation: React docs

Setting initial value for computed property with vuejs

I'm trying out vuejs by following along with the laracasts series of webcasts on this. In https://laracasts.com/series/learning-vue-step-by-step/episodes/6, Jeffery Way has put the code in the http://jsfiddle.net/d4f27e5p/ .
The initial setting is shown in the screenshot, before any plan is selected. I would like to set a default value in the button of "please select " (instead of "Downgrade") The button code is:
<span v-else>
<button #click="setActivePlan">
{{ isUpgrade ? 'Upgrade' : 'Downgrade' }}
</button>
How can I do this?
How about adding a computed property for the button text that includes the additional logic? Something like this:
buttonText: function() {
if(!this.active.name)
return "Please Select";
return this.isUpgrade ? 'Upgrade' : 'Downgrade';
}
Then the button would use this:
<span v-else>
<button #click="setActivePlan">
{{ buttonText }}
</button>
</span>
Here's an updated jsfiddle.

Categories

Resources