Search code examples
reactjscomponentschildren

How to render children as string in React, in reusable component


I have created reusable component in React- reusableToolbar which I want to render some text inside, which is children. How to render this component and pass children prop ?

This is how component looks like

   import React, { FC } from "react";
import { ReusableToolbarWrapper, StyledText } from "./styles";
import CloseIcon from "@material-ui/icons/Close";

export interface ReusableToolbarProps {
  childred: string;
}
export const ReusableToolbar: FC<ReusableToolbarProps> = (children) => {
  return (
    <ReusableToolbarWrapper>
      <CloseIcon
        style={{
          width: "14px",
          height: "14px",
          marginLeft: "20px",
          marginTop: "22px",
          marginBottom: "24px",
        }}
      />
      <StyledText>{children}</StyledText>
    </ReusableToolbarWrapper>
  );
};

And how should I render it here : ?

    import {Toolbar} from "./toolbar";
import {ReusableToolbar} from "./ReusableToolbar/ReusableToolbar.tsx";

function App() {
  return (
      <ReusableToolbar></ReusableToolbar>
      // <Toolbar/>
    
  );
}

export default App;

thanks


Solution

  • children is the prop that goes inside the tags like this

    import {Toolbar} from "./toolbar";
    import {ReusableToolbar} from "./ReusableToolbar/ReusableToolbar.tsx";
    
    function App() {
      return (
          <ReusableToolbar>Hello world</ReusableToolbar>
          // <Toolbar/>
        
      );
    }
    
    export default App;
    

    you can alternatively pass it as a regular prop like this

    import {Toolbar} from "./toolbar";
    import {ReusableToolbar} from "./ReusableToolbar/ReusableToolbar.tsx";
    
    function App() {
      return (
          <ReusableToolbar children="Hello world" />
          // <Toolbar/>
        
      );
    }
    
    export default App;