Taha Azzabi
Taha Azzabi

Reputation: 2570

ReactJS - Difference between generates a unique id via default props and state

For some reason i need to generate some unique ID to use them as CSS ID Selectors in a ReactJs component , I've done two examples:

1) Defining a random value in default props, see Test with default props below

=>It doesn't work

2) Defining a random value in state see Test with state below

=>It works

Can some one explain why when i use default props i've got always the same value?

Codesanbox :

Codesanbox link with all code example

Source code :

function App() {
      return (
        <div className="App">
          <h1>Components with random default props</h1>
          <DymmyComponentProps />
          <br />
          <DymmyComponentProps />
          <br />
          <DymmyComponentProps />
          <br />
          <DymmyComponentProps />
          <h1>Components with random state</h1>
          <DymmyComponenState />
          <br />
          <DymmyComponenState />
          <br />
          <DymmyComponenState />
          <br />
          <DymmyComponenState />
        </div>
      );
    }

Test with default props:

  class DymmyComponentProps extends Component {
          static defaultProps = {
            id: `Unique id is: ${Math.random()
              .toString(36)
              .substring(7)}`
          };

          render() {
            const { id } = this.props;
            return <p id={id}>{id}</p>;
          }
        }

Test with state : (it work)

class DymmyComponenState extends Component {
  state = {
    id: `Unique id is: ${Math.random()
      .toString(36)
      .substring(7)}`
  };

  render() {
    const { id } = this.state;
    return <p id={id}>{id}</p>;
  }
}

Upvotes: 1

Views: 360

Answers (1)

Vencovsky
Vencovsky

Reputation: 31595

Can some one explain why when i use default props i've got always the same value?

As you can see, defaultProps is a static property

static defaultProps = { 
    ...
};

Wich means it doesn't change on every new class, it's the same for every class.

And if you think about it, if the value is different on every instance of the class, it wouldn't be considered default, and in your case, it shouldn't be.

Upvotes: 2

Related Questions