Languages
[Edit]
EN

React - how to add attributes to dynamic tag name

0 points
Created by:
Hayley-Mooney
377

In this article, we would like to show you how to add attributes to dynamic tag name in React.

Below we create three tags using dynamic tag names and pass different style attributes to components with different priority attributes.

Note:

In this article, we describe how to create dynamic tag names.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

// style objects -------------------------

const style1 = {
  color: 'orange',
};

const style2 = {
  color: 'lightgreen',
};

const style3 = {
  color: 'blue',
};

// dynamic tag name -------------------------

const MyComponent = (props) => {
  const CustomTag = `h${props.priority}`;
  return <CustomTag style={props.style}>priority = {props.priority}</CustomTag>;
};

// adding style attribute ------------------------- 

const App = () => {
  return (
    <div>
      <MyComponent style={style1} priority="1" />
      <MyComponent style={style2} priority="2" />
      <MyComponent style={style3} priority="3" />
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Related posts

ReactJS

React - add attributes to dynamic tag name
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join