Home > Software engineering >  How do I change the string value based on what it contains in react?
How do I change the string value based on what it contains in react?

Time:03-04

Let’s say I want to show different copy (e.g “shoes”) depending on the text in the string {variant_prod.title}

So for example:

   if (variant_prod_title == 'Nike air shoes' ) { 
        Change so "shoes" will be the only thing showing in the string
        else if (variant_prod_title == 'Nike air t-shirt' ) {
        Change so "t-shirt" will be the only thing showing in the string
    } 
        }

Here’s how the code looks like for me in my react component, how do change so it only shows “shoes” for example?

<span >{variant_prod.title}</span>

CodePudding user response:

This is how you can achieve this in a way that it doesn't matter if your title is 'Nike air shoes' or 'Puma shoes'. As long as it includes shoes or t-shirt the displayed value will be set accordingly.

// this sets the initial value to the entire string
let displayedValue = variant_prod.title;

// this if checks if the word e.g. 'shoes' or 't-shirt' is present in the title
if (variant_prod.title.includes('shoes')) {
    displayedValue = 'shoes';
}    
else if (variant_prod.title.includes('t-shirt')) {
    displayedValue = 't-shirt';
}

return (
    <span >{displayedValue}</span>
)

CodePudding user response:

A simple way to implement what you are looking for is by using Conditional (ternary) operator

It's a good practice to use strict comparison "===" and declare your comparisons in a variable.

You can try the following code by using ES6:

const NIKE_AIR_SHOES = 'Nike air shoes';
const NIKE_AIR_TSHIRT = 'Nike air t-shirt';

<span >
  {variant_prod.title === NIKE_AIR_SHOES
    ? "Shoes"
    : variant_prod.title === NIKE_AIR_TSHIRT
    ? "t-shirt"
    : ""}
</span>

You can also use the Logical AND (&&) as well as the Logical OR (||) operator to implement this.

<span >
  {(variant_prod.title === NIKE_AIR_SHOES && "Shoes") ||
    (variant_prod.title === NIKE_AIR_TSHIRT && "t-shirt") ||
    ""}
</span>;

CodePudding user response:

If your title has consistent structure and always have the output as the third value in the string then you can simply use

<span >{variant_prod.title.split(' ')[2]}</span>

variant_prod.title.split(' ') will convert the title into an array of 3 elements and you can use whatever value you want

'Nike air shoes' will return shoes

'Nike air t-shirt' will return t-shirt

'Nike air anything-else' will return anything-else

  • Related