developer2015
developer2015

Reputation: 423

React this.props not working as expected

I am in the process of learning React and trying a sample code from a book. The code is simple it is supposed to display vowels in different colors defined in the ReactDOM.render but instead it displays them all in one color coming from the style tag.

Attached below is the code

<!DOCTYPE html>
<html>

<head>
    <meta charset-="utf-8'">
    <title>Styling in React</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>

    <style>
        #container {
            padding: 50px;
            background-color: #FFF;
        }

        div div div {
            padding: 10px;
            margin: 10px;
            background-color: #ffde00;
            color: #333;
            display: inline-block;
            font-family: monospace;
            font-size: 32px;
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="container"></div>
    <script type="text/babel">
var destination = document.querySelector("#container");
class Letter extends React.Component {
    render() {
        var letterStyle =  {
    padding:10,
    margin:10,
    backgroundColor:this.props.bgcolor,
    color:"#333",
    display:"inline-block",
    fontFamily:"monospace",
    fontSize:32,
    textAlign:"center"
        };
        return (
                <div>
                    {this.props.children}
                </div>
              );
    }
}
ReactDOM.render(
        <div>
        <Letter bgcolor="#58B3FF">A</Letter>
        <Letter bgcolor="#FF605F">E</Letter>
        <Letter bgcolor="#FFD52E">I</Letter>
        <Letter bgcolor="#49DD8E">O</Letter>
        <Letter bgcolor="#AE99FF">U</Letter>
        </div>,
        destination
           );
        </script>
</body>

</html>
}

Upvotes: 0

Views: 1764

Answers (2)

Tetsuya3850
Tetsuya3850

Reputation: 1019

Try {this.props.bgcolor} you need a {} to use dynamic variables.

Upvotes: 0

jaredkwright
jaredkwright

Reputation: 1380

It looks like you aren't using letterStyle anywhere. Try the following:

render() {
  var letterStyle =  {
    padding:10,
    margin:10,
    backgroundColor:this.props.bgcolor,
    color:"#333",
    display:"inline-block",
    fontFamily:"monospace",
    fontSize:32,
    textAlign:"center"
  };
  return (
    <div style={letterStyle}>
       {this.props.children}
    </div>
  );
}

Upvotes: 2

Related Questions