56

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?

5
  • 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. Commented Aug 30, 2015 at 0:00
  • 1
    possible duplicate of Are there constants in JavaScript? Commented Aug 30, 2015 at 0:01
  • 3
    I am asking, how would you have that code in reactjs? Commented Aug 30, 2015 at 0:39
  • 1
    The same way I would in plain JavaScript. Commented Aug 30, 2015 at 0:41
  • 1
    Just a regular old statement. var sizeToLetterMap = ...; Commented Aug 30, 2015 at 9:24

8 Answers 8

49

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. I've used this solution a similar way for refreshing a component. constructor(props) { super(props); this.state = initialState }' 'reset(){ this.setState(initialState) }
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];
    }

1 Comment

I believe in this case, you can access the static properties without having to instantiate the class. e.g. const staticFromClass = MyComponent.someOtherStatic // => 100
16

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

1 Comment

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. } >> ```
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

3 Comments

Using stage-0 functionalities is extremely risky, as they may dramatically change or not even exist in the next realease of the language.
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?
Take the current implementation of statics: static get bar() { return _bar; } and static set bar(value) { _bar = value; } in es6
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',
})

1 Comment

Parsing error: Unexpected token
0

You can also do,

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

now access, those constant (default value) using

@props.firstName

@props.lastName

Hope this help!!!.

Comments

0
enter code here
import React from "react";

// Mapping of size_text to size letter
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 {
  // Optimized photoUrl method to return a URL string
  photoUrl(image, sizeText) {
    const sizeLetter = sizeToLetterMap[sizeText] || '';
    return `https://example.com/images/${image}_${sizeLetter}.jpg`;
  }

  render() {
    const { image, size_text } = this.props; // Destructuring props for cleaner code

    return (
      <div className="photo-wrapper">
        {/* Display the generated URL */}
        The URL is: <a href={this.photoUrl(image, size_text)} target="_blank" rel="noopener noreferrer">
          {this.photoUrl(image, size_text)}
        </a>
      </div>
    );
  }
}

export default PhotoComponent;

// Usage: 
// <PhotoComponent image="abc.png" size_text="thumbnail" />

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.