zhichun wang
zhichun wang

Reputation: 21

what is difference between the following methods about React element type

I'm writing react apps with following codes. one is ok, the other run error. I want to know the difference between these code.

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
  photo: PhotoStory,
  video: VideoStory
};


function Story() {
  // programer run ok
  return <components.photo />;
}

function Story() {
  // programer run with errors
  return <components["photo"] />;
}

Upvotes: 2

Views: 58

Answers (1)

Will Jenkins
Will Jenkins

Reputation: 9787

The error is caused by the fact that the square bracket version is not valid JSX, so the parser doesn't know how to interpret it. The dot notation is valid syntax, and is a common way to compose components.

What you can do is this:

function Story() {
  const PhotoComponent = components["photo"]; //jsx parser not involved here
  return <PhotoComponent />;
}

See the JSX in depth React docs for more info

Upvotes: 1

Related Questions