0

Is it possible to assign component to variable in React? I want something like this:

records[0] = {
  return(
    <Row key={'myValue'}>
      {myValue}
    </Row>
  )
}

records[0] = {
  return(
    <Row key={'mySecondValue'}>
      {mySecondValue}
    </Row>
  )
}

So then I can sort this array (records) based on other array and display.

2
  • 1
    Sure, but having a return there is nonsensical. So are the curly-braces. And two records[0]. But that's not how you'd do it IRL, you'd have an array of data, each element rendered by a component, and when it's sorted, it would be re-rendered. Commented Jan 12, 2018 at 16:01
  • Thanks for answer Dave! Yeah, there should be records[1] in second element of array. I also wrote it with "return", because thats how am I doing this while using map function. Sorry for mistakes. Commented Jan 13, 2018 at 15:19

2 Answers 2

1

Sure, you can just do :

const records = [
  <Row key={'myValue'}>{myValue}</Row>,
  <Row key={'mySecondValue'}>{mySecondValue}</Row>
]
Sign up to request clarification or add additional context in comments.

2 Comments

for bigger structures you can wrap components into parenthesis
Thank you dashton and zmii!
0

there is two ways:

const Element = ({title}) => <h1>{title}</h1>;

//as a callback
elements[0] = ({title}) => <Element title={title}/>;

//and then invoke it like:
const anotherElement = () => <>{elements[0]('MyTitle')</>

//or
elements[0] = ({title}) => Element;
const anotherElement = () => <elements[0] title={'MyTitle'}/>

Comments

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.