Search code examples
javascriptreactjsclass-fields

Class fields from properties in ReactJS


I am having trouble figuring out how to correctly create a class field based on a property.

class Example extends Component {
  example_titles = props.titles;

  // ...
}

which results in

Line 7:  'props' is not defined  no-undef

I call this class in another file that works 100% correctly unless I add this tag with the following call <Example titles={["titles"]} />

I am using the stage 2 in Babel to eliminate constructors. I am aware of how to do this with constructors, but am struggling to understand this without them.


Solution

  • You can access the props in class properties with this.props.

    class Example extends React.Component {
      example_titles = this.props.titles;
    
      render() {
        return (
          <div>
            {this.example_titles.map((title, index) => (
              <div key={index}>{title}</div>
            ))}
          </div>
        );
      }
    }
    
    ReactDOM.render(
      <Example titles={["titles"]} />,
      document.getElementById("root")
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id="root"></div>