Home How to set element name dynamically in ReactJS
Reply: 2

How to set element name dynamically in ReactJS

Thidasa Paranavitharana
1#
Thidasa Paranavitharana Published in 2018-02-14 10:15:29Z

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>
 )
}
omerts
2#
omerts Reply to 2018-02-14 10:34:15Z

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

pwolaq
3#
pwolaq Reply to 2018-02-14 10:42:20Z

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>
    )
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.351448 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO