2

I have a list of array, I would want to match the string with component name, is that possible? I tried this https://codesandbox.io/s/lpzq3jvjm7

function App() {
  const obj = {
    name: "Name"
  };

  const capitalize = (s) => {
    if (typeof s !== 'string') return ''
    return s.charAt(0).toUpperCase() + s.slice(1)
  }

  return (
    <div className="App">
      {React.createElement(capitalize(obj.name), {
        name: "james"
      })}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

doesn't seem to work, any clue?

2
  • @CodeManiac what if I alrdy have the component but it's at other file? codesandbox.io/s/5k41vv116n Commented Mar 7, 2019 at 4:19
  • You can import from that file import Name from whatever path of that file Commented Mar 7, 2019 at 4:20

1 Answer 1

3

It's hard to tell what error you were actually running into since you didn't have a component called Name. Simple fix?

function Name(props) {
  return props.name
}

function App() {
  const obj = {
    name: Name
  };

  return (
    <div className="App">
      {React.createElement(obj.name, {
        name: "james"
      })}
    </div>
  );
}

Prints james on the page.

Update

You are missing a few things.. firstly importing your component

import Name from './Name'

and inside Name.js you were missing the react import

import React from 'react'
export default ({ name }) => <h1>my name is {name}</h1>;

and make sure to set the actual value of Name to your object, not a string `"Name"

const obj = {
  name: Name
};

codesandbox

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

I have the Name component,it is at Name.js

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.