Thidasa Pankaja
Thidasa Pankaja

Reputation: 1070

How to set element name dynamically in ReactJS

How can I set element name dynamically in reactjs ? I'm using this library to show cryptocurrecy icons as a list. Using the library we can get Bitcoin icon as <Btc /> and so on. Lets say I've define an array of Cryptocurrency names(Btc, Eth, Sc etc) as a state call crypto. Using map function how can I set the element name dynamically ?

render(){
 return(
  <div>
   {this.state.crypto.map( crypto => {
    <h3>{crypto}</h3>
    <{crypto} />
   }
  </div>
 )
}

Upvotes: 0

Views: 652

Answers (2)

pwolaq
pwolaq

Reputation: 6381

You can simply use variable as tag (the only requirement is that variable starts with uppercase letter):

render(){
    return(
        <div>
            {this.state.crypto.map(Crypto => (
                <div>
                    <h3>{crypto}</h3>
                    <Crypto />
                </div>
            ))}
        </div>
    )
}

Upvotes: 2

omerts
omerts

Reputation: 8838

You can set the name dynamically using React.createElement function. JSX is just synthetic sugaring over the createElement function.

render() {    
 return (
  <div>
   {this.state.crypto.map(crypto => {
      const cryptoElement = React.createElement(crypto)
      return <div>
        <h3>{crypto}</h3>
        {cryptoElement}
      </div>
    })}
  </div>
 )
}

Fiddle: https://jsfiddle.net/omerts/Lagja2sy/

Here you can find the documentation about it: https://reactjs.org/docs/react-api.html#createelement

Upvotes: 1

Related Questions