Home > Enterprise >  How I can create a simple React component rendered as a <div> which takes a text value and a f
How I can create a simple React component rendered as a <div> which takes a text value and a f

Time:05-19

I'm new in the world of React and after see tutorials and made some codes I wanted to know if I can add attributes like value and color to a div. I mean, How I can return Hello World with color. The follow is an example:

<div style="color: red;">Hello World!</div>

I tried with constructor function, but I can't render the color and the value of "Hello World!

CodePudding user response:

In a JSX file you'd use <div style={{color: 'red'}}>Hello World!</div>

CodePudding user response:

I would use a class for this.

function Example() {
  return (
    <div className="red">
      Hello world!
    </div>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
.red { color: red; }
<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="react"></div>

Or, if you're passing props into another component, you can still use this method. Just pass the colour as a prop, and then use className={color}.

function Example() {
  return <Hello color="red" />
}

function Hello({ color }) {
  return (
    <div className={color}>
      Hello world!
    </div>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
.red { color: red; }
<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="react"></div>

  • Related