Writing a ReactJS component that renders rendering

I have a component H1:

<H1 importance={importance}>foo</H1>

I want the rendering to H1depend on importanceprop.

So I tried:

import styled from 'styled-components';

const Default = styled.h1`
  font-size: 1.2em;
`;

const High = styled.h1`
  font-size: 2.2em;
`;

function H1({ importance }) {
  return importance === 'HIGH' ? 
    (<High props={...props}/>) : 
      (<Default props={...props}/>);
}

export default H1;

But I get:

A valid React (or null) element must be returned. You may have undefined returns, an array, or some other invalid object.

Why is this?

I also want the content ("foo" here) to appear inside the child component. How can i achieve this?

+4
source share
1 answer

A valid React (or null) element must be returned. You may have returned undefined, an array, or some other invalid object.

, ... , , ...


, ( "foo" ) . ?

function H1({ importance, children }) {

  return importance === 'HIGH' 
    ? (<High>{children}</High>) 
    : (<Default>{children}</Default>);
}

Update

, Object Spread Operator :

function H1(props) {

  return importance === 'HIGH' 
    ? (<High {...props} />) 
    : (<Default {...props} />)
  ;
}
+3

Source: https://habr.com/ru/post/1682864/


All Articles