Is it possible to align a div based on a condition? - javascript

I have a div which I have set to align="right". I have created a local variable called userId and assigned 1 to it and I am wondering if is possible to somehow set the div to left align if userId === 1, which will be the case. I've tried reading the react docs on conditional rendering but I don' believe that is what I'm looking for as they all deal with rendering whereas the div that I want to align is being returned by an export function so the render function isn't used.
export function MessageRow({ message, fetch }) {
return (
<div>
<br />
<div align="right" className="Message-Body">
<div className="Message-row-header">{message.user}</div>
<div>{message.content}</div>
<div className="muted-text">
(Sent: {new Date(message.timestamp).toUTCString()})
</div>
<div>
<button
className="block"
onClick={() => messageService.delete(message.id).then(fetch)}
>
Delete
</button>
<button className="block">Edit</button>
</div>
</div>
</div>
);
}
This is what I currently have and was thinking of trying a function like below but I am unsure how I would then get it to apply to the div.
function checkMessageUserID(userId) {
if (userId === 1) {
}
}

It is still being used from a render() point of view though, no?
So you could still do what you want:
return (
<div><br />
{userId !== 1 ?
<div align="right" className="Message-Body">
:
<div align="left" className="Message-Body">
}
...

1) You can return JSX from the function and call the function inside return.
function checkMessageUserID(userId) {
if (userId === 1) {
<div align="right" className="Message-Body">
}
else{
<div align="left" className="Message-Body">
}
}
Then inside return call {checkMessageUserID()}
2) You can also use ternary operator inside your render.
<div align = {userID == 1 ? "right" : "left"} className="Message-Body">

Conditional rendering works the same for functional as well as stateful components.
Working code snippet below.
<div align={userId === 1 ? 'left' : 'right' } className="Message-Body">

You could do any of the above, or what I would recommend is, you create two styling classnames, you can call them 'left/right-message' or 'mine/otherPerson-message' and you can assign align: 'left/right' to each, you can even assign different colors for that chat feel, you'd achieve this simply by doing:
<div className={userId === 1 ? "left-message" : "right-message" >
...
</div>

Related

Moving conditional element rendering into a separate function within the same component

I'm trying to move a part of the code where it gets very repetitive into a function within the same component.
Here is what it would look like before moving this conditional statement into a separate function...
<div className="col-4">
{parts.map(part => (
part.active[0] && <div key={part.bodyPart}>{part.bodyPart}</div>
))}
</div>
and I'm trying to move it so it would look something like this in the function.
const showParts = (activeIndex) => {
return parts.map(part => (
//this one does not work
part.active[activeIndex] && <div key={part.bodyPart}>{part.bodyPart}</div>
//but for some reason, this works below without the conditional statement
/* <div key={part.bodyPart}>{part.bodyPart}</div> */
))
}
And here's what it would look like in the return statement.
return (
<div className="container text-center">
<div className="row rows-cols-3">
<div className="col-4">
{showParts(0)}
</div>
</div>
</div>
);
I know that the conditional statement is causing the issue but I'm not sure what bracket or return statement I'm missing in the function to make it work.
It's also confusing because I am not getting any error with the conditional statement I have it on here.
Also, here's what the 'parts' state looks like.
const [parts, setParts] = useState([
{ bodyPart: "upperLip", price: 1000, active: [true, true, true] }]
Thanks!

How to get this value in a variable and use it in a conditional in React?

I would appreciate any help in getting this sorted out. In the code below I would like to take the values between `` from the span and assign them to a variable in order to have the following logic:
${research.data.codesRelated[1].code} === undefined
? ${research.data.description}
: ${research.data.codesRelated[1].code} ${research.data.description}
How can I do this? It seems so easy but I couldn't sort it out, don't know where to place the const & conditional rendering inside the code and to make it work. Everyone in advance.
The code is below:
const Research: FC<ResearchProps> = memo(
({ research, hideLabel = false, intl }) => (
<div className="section research">
<div className="section__value" id="container-research-value">
<div className="research-info">
<div className="description" id="element-research-description">
<PopoverWrapper
id="element-research-description-tooltip"
trigger="hover"
placement="top"
speaker={<span className="text-tooltip">{research.data.description}</span>}
>
**<span>{`${research.data.codesRelated[1].code} ${research.data.description}`}</span>**
</PopoverWrapper>
</div>
You can try this
const Research: FC<ResearchProps> = memo(
({ research, hideLabel = false, intl }) => (
<div className="section research">
<div className="section__value" id="container-research-value">
<div className="research-info">
<div className="description" id="element-research-description">
<PopoverWrapper
id="element-research-description-tooltip"
trigger="hover"
placement="top"
speaker={<span className="text-tooltip">{research.data.description}</span>}
>
<span>{research.data.codesRelated[1].code === undefined ?
research.data.description
: <>
{research.data.codesRelated[1].code} {research.data.description}
</>}
</span>
</PopoverWrapper>
</div>
As already was mentioned, you can use the ternary operator.
You can use a simple hack: conditional rendering for code with space at the end of the string template.
<span>
{research.data.codesRelated[1].code && `${research.data.codesRelated[1].code} `}
{`${research.data.description}`}
</span>
But the best way to create an external function for build this string. And your render will be like this:
<span>
{buildResearchDescription(research.data)}
</span>

React conditionally show link if there is content on json file?

Did some searching around, but could not find anything. this is something simple on jQuery and Rails, but not sure if there is a correct way to to this in React. I have this component that is grabbing its data form a JSON file, and I want to only display a certain link if the JSON has content, otherwise I want to hide it. I tried this way so far with no luck:
renderList(projectLinks){
//let self = this;
return projectLinks.map(function(link) {
var showDemo = "";
if(link.urlDemo === ""){
console.log("i'm empty");
showDemo = "displayNone";
}
return <Panel header={link.title} eventKey={link.eventKey} key={link.title}>
<p>{link.description}</p>
<img src={link.image} className="img-thumbnail" alt="project thumbnail"/><br />
<a href={link.urlDemo} className={showDemo}>Demo </a>
<a href={link.urlCode}>Code </a>
</Panel>
});
}
so, if the json link is empty like this: "urlDemo": "", I want the link to be hidden.
Appreciate the help.
Inside render, use conditional operator. Here's an example
render(){
return (
<div>
{this.state.check ? <div>Show this if check is true</div> :
<div>Show this if check is false</div>}
<div>
)
}
Edit: A more specific example
render(){
return(
<div>
{link.urlDemo ? <a href={link.urlDemo}>Demo </a> : null}
</div>
)
}
Another way of doing the same:
render(){
return(
<div>
{link.urlDemo && <a href={link.urlDemo}>Demo </a>}
</div>
)
}

*ngIf window.location.href.indexOf is not working

I need to show one element only if location is right, if not, it shoudn't be shown.
This is not working:
<div *ngIf="!accessTrue() && window.location.href.indexOf('something')" > -1)>
CODE
</div>
you cannot access the window object inside the template.
But you can define a getter in your component :
get hasSomething(){
return window.location.href.indexOf('something') > -1
}
then :
<div *ngIf="!accessTrue() && hasSomething">
CODE
</div>
Note that it might be cleaner to use an ActivatedRoute if your parameter is accessible through it.
In HTML :
<div *ngIf="hasAccess"> CODE </div>
In angular Component :
constructor(){
this.hasAccess = window.location.href.indexOf('something') > -1 && !this.accessTrue();
}

How to apply rules to only certain elements in array

I have this loop in react:
<div>
{this.state.dealersDeck.map(function(card, index){
return <div className="cardFormatDH" key={ index }> {card.rankKey}{card.suit} </div>;
}, this)}
</div>
This goes through an array of objects and then renders them on screen. This is all good except I would like to format it so I only display the contents at certain points. i.e. I'm creating blackjack and I don't want the dealers second card to be visible until the end.
I may have to show more code but was wondering if map had some sort of attribute that I could use.
You could add a boolean prop to each card and render based on that:
<div>
{this.state.dealersDeck.map(function(card, index){
return { card.display &&
<div className="cardFormatDH" key={ index }>{card.rankKey} {card.suit} </div>
}
}, this)}
</div>
You can use basic If...Else statements inside map function as well. Moreover you can write more business logic also to add more functionality.
var cardsHTML = this.state.dealersDeck.map(function(card, index){
if(condition...1){
return <div className="cardFormatDH" key={ index }> {card.rankKey}{card.suit} </div>
}
if(condition...2){
return <div></div>
}
}

Categories