54

I have a function that maps text to letters:

sizeToLetterMap: function() { 
     return {
                small_square: 's',
                large_square: 'q',
                thumbnail: 't',
                small_240: 'm',
                small_320: 'n',
                medium_640: 'z',
                medium_800: 'c',
                large_1024: 'b',
                large_1600: 'h',
                large_2048: 'k',
                original: 'o'
            };
}

these letters are used to create flickr photo urls. So, the photoUrl function takes in a image object and size text object and calls the sizeToLetterMap to come up with the letter for that size text.

The function:

photoUrl(image, size_text): function () {
      var size = this.sizeToLetterMap(size_text);
}

I don't think its proper design to have the sizeToLetterMap as a function. I think it fits better as a constant. How can I define constants in ReactJS?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • 4
    React is just a library for JavaScript. React does not subsume JavaScript. In particular, when you go down to something as unrelated from UI code as how to declare constants, you really shouldn’t be asking how React lets you do that, but rather how to go about doing that in JavaScript in general. – icktoofay Aug 30 '15 at 00:00
  • 1
    possible duplicate of [Are there constants in JavaScript?](http://stackoverflow.com/questions/130396/are-there-constants-in-javascript) – icktoofay Aug 30 '15 at 00:01
  • 3
    I am asking, how would you have that code in reactjs? – Chris Hansen Aug 30 '15 at 00:39
  • 1
    The same way I would in plain JavaScript. – icktoofay Aug 30 '15 at 00:41
  • 1
    Just a regular old statement. `var sizeToLetterMap = ...;` – Chris Martin Aug 30 '15 at 09:24

7 Answers7

48

You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.

import React from "react";

const sizeToLetterMap = {
  small_square: 's',
  large_square: 'q',
  thumbnail: 't',
  small_240: 'm',
  small_320: 'n',
  medium_640: 'z',
  medium_800: 'c',
  large_1024: 'b',
  large_1600: 'h',
  large_2048: 'k',
  original: 'o'
};

class PhotoComponent extends React.Component {
  constructor(args) {
    super(args);
  }

  photoUrl(image, size_text) {
    return (<span>
      Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
    </span>);
  }

  render() {
    return (
      <div className="photo-wrapper">
        The url is: {this.photoUrl(this.props.image, this.props.size_text)}
      </div>
    )
  }
}

export default PhotoComponent;

// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";
Rohanthewiz
  • 947
  • 9
  • 9
  • Perfect. I've used this solution a similar way for refreshing a component. `constructor(props) { super(props); this.state = initialState }' 'reset(){ this.setState(initialState) }` – Steve Taylor Nov 14 '17 at 05:43
32

If you want to keep the constants in the React component, use statics property, like the example below. Otherwise, use the answer given by @Jim

var MyComponent = React.createClass({
    statics: {
        sizeToLetterMap: {
            small_square: 's',
            large_square: 'q',
            thumbnail: 't',
            small_240: 'm',
            small_320: 'n',
            medium_640: 'z',
            medium_800: 'c',
            large_1024: 'b',
            large_1600: 'h',
            large_2048: 'k',
            original: 'o'
        },
        someOtherStatic: 100
    },

    photoUrl: function (image, size_text) {
        var size = MyComponent.sizeToLetterMap[size_text];
    }
Ed Ballot
  • 3,405
  • 1
  • 17
  • 24
  • 1
    I believe in this case, you can access the `static` properties _without_ having to instantiate the class. e.g. `const staticFromClass = MyComponent.someOtherStatic // => 100` – codeful.element Apr 26 '17 at 18:58
15

well, there are many ways to do this in javascript just like other says. I don't think there's a way to do it in react. here's what I would do:

in a js file:

module.exports = {
    small_square: 's',
    large_square: 'q'
}

in your react file:

'use strict';

var Constant = require('constants');
....
var something = Constant.small_square;

something for you to consider, hope this helps

Jim
  • 1,123
  • 13
  • 29
  • upvoting as this was exactly what I was looking for... I had something like this ``` import constants from "../../util/constants" const CONSTANTS = constants << Inside one of the functions of React.Component class test() { constants.URL // error CONSTANTS.URL // succeed. } >> ``` – stanley_manley Apr 12 '21 at 18:23
6

Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases

You can use ES7 statics:

npm install babel-preset-stage-0

And then add "stage-0" to .babelrc presets:

{
    "presets": ["es2015", "react", "stage-0"]
}

Afterwards, you go

class Component extends React.Component {
    static foo = 'bar';
    static baz = {a: 1, b: 2}
}

And then you use them like this:

Component.foo
Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
e18r
  • 7,578
  • 4
  • 45
  • 40
  • 2
    Using stage-0 functionalities is extremely risky, as they may dramatically change or not even exist in the next realease of the language. – Marco Scabbiolo Aug 11 '16 at 15:45
  • Hey that's a very important point. I'll add it to my answer. However, what could possibly change about such simple constructs as statics? – e18r Aug 11 '16 at 15:50
  • Take the current implementation of statics: `static get bar() { return _bar; }` and `static set bar(value) { _bar = value; }` in es6 – Marco Scabbiolo Aug 11 '16 at 15:55
2

You can create constants in separate file as below

export const param = Object.freeze({
  ELECTRICITY:      'Electricity',
  GAS_FUEL_THERMAL: 'GasFuelsAndThermals',
  WATER:            'Water',
  WASTE:            'Waste',
  CARBON:           'Carbon',
})
0

You can also do,

getDefaultProps: ->
  firstName: 'Rails'
  lastName: 'React'

now access, those constant (default value) using

@props.firstName

@props.lastName

Hope this help!!!.

AMIC MING
  • 6,306
  • 6
  • 46
  • 62
-2

export const param = Object.freeze({ ELECTRICITY: 'Electricity', GAS_FUEL_THERMAL: 'GasFuelsAndThermals', WATER: 'Water', WASTE: 'Waste', CARBON: 'Carbon', })

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 07 '22 at 23:06