简体   繁体   中英

When I log mixedCategory is firstName[object Object]lastName, How to insert icon inside a string

state = { icon: , }

loadAllCategories = async () => 
{ 
  const{icon} = this.state; 
  firstCategory ="Electronic Devices";
  lastCategory = "Phone"; mixedCategory =firstCategory+ icon + lastCategory;
};

You need to return as a jsx value as shown below, for wrapping you can use React.Fragments

let mixedCategory = (
  <>
    {firstCategory} {icon} {lastCategory}
  </>
);

Code

import React, { Component } from "react";
import ReactDOM from "react-dom";

const Icon = () => {
  return (
    <svg height="100" width="100">
      <circle
        cx="50"
        cy="50"
        r="40"
        stroke="black"
        stroke-width="3"
        fill="red"
      />
      Sorry, your browser does not support inline SVG.
    </svg>
  );
};

class App extends Component {
  state = { icon: <Icon />, mixedValue: null };

  loadAllCategories = () => {
    const { icon } = this.state;
    let firstCategory = "Electronic Devices";
    let lastCategory = "Phone";
    let mixedCategory = (
      <>
        {firstCategory} {icon} {lastCategory}
      </>
    );
    this.setState({
      mixedValue: mixedCategory
    });
  };

  render() {
    return (
      <>
        <button onClick={this.loadAllCategories}>Click here</button>
        {this.state.mixedValue && this.state.mixedValue}
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

see the working example in the codepen

@Update

as mentioned in the comments using FontAwesomIcon

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { library } from "@fortawesome/fontawesome-svg-core";
import { fab } from "@fortawesome/free-brands-svg-icons";
import { faInfo, faCoffee } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

library.add(fab, faInfo, faCoffee);

class App extends Component {
  state = { icon: <FontAwesomeIcon icon="info" />, mixedValue: null };

  loadAllCategories = () => {
    const { icon } = this.state;
    let firstCategory = "Electronic Devices";
    let lastCategory = "Phone";
    let mixedCategory = (
      <>
        {firstCategory} {icon} {lastCategory}
      </>
    );
    this.setState({
      mixedValue: mixedCategory
    });
  };

  render() {
    return (
      <>
        <button onClick={this.loadAllCategories}>Click here</button>
        {this.state.mixedValue && this.state.mixedValue}
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM