Nancy Moore
Nancy Moore

Reputation: 2470

How to tag results separately in React

I have a record that I displayed in React.

The record contains values that are separated by commas as per below tag1,tag2,tag3,tag_new,tag_old.

Here is my issue: I need to create tag of the records as it is being separated by commas.

The screenshot below will show what am trying to achieve:

enter image description here

Here is the code:

//import goes here
const App = () => {

const record = {
    my_tags: 'tag1,tag2,tag3,tag_new,tag_old',
  };
const style = {
      color: 'white',
      background: 'blue',
borderRadius: '20px'
    };



  return (
    <div>
   
          
Display Tags

      <div>
           <br />
        
<span style={style}>{record.my_tags}</span>


          
  <br /> 
     </div>

    </div>
  );
};

Upvotes: 0

Views: 128

Answers (2)

Ryan Le
Ryan Le

Reputation: 8412

You could split them and map them to make it as you desired

Like so:

    const App = () => {
      const record = {
        my_tags: "tag1,tag2,tag3,tag_new,tag_old"
      };
      const style = {
        color: "white",
        background: "blue",
        borderRadius: "20px"
      };

      return (
        <div>
          Display Tags
          <div>
            <br />
            {record.my_tags.split(",").map((tag) => (
              <span key={tag} style={style}>{tag}</span>
            ))}
            <br />
          </div>
        </div>
      );
    };

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

Upvotes: 2

kup
kup

Reputation: 819

//import goes here
const App = () => {

const record = {
    my_tags: 'tag1,tag2,tag3,tag_new,tag_old',
  };
const style = {
      color: 'white',
      background: 'blue',
borderRadius: '20px'
    };



  return (
    <div>
   
          
Display Tags

      <div>
           <br />
        {
          record.my_tags.split(',').map((item)=>{
           return <span style={style}>{item}</span>
           })
         }


          
  <br /> 
     </div>

    </div>
  );
};

Upvotes: 0

Related Questions