Home > Software engineering >  How to add JSX inside props?
How to add JSX inside props?

Time:10-04

I have a component which has props value. This component is global and I don't want to change its source code. I want to add pre tag inside the value prop to have a proper indentation between title and value.

<component
   title = {<strong>Name</strong>}
   value = {<pre>  {name === undefined ? myName : myNames}</pre>}
/>

Issue: I get NaN for value prop.
How do I fix it?
Also, is there a way to add a gap/padding between title and value? Please note that I do not wish to modify the source file of Component.

CodePudding user response:

Whenever I face a situation like this, my first approach is to make a helper function to render the smaller parts and pass them as props while invoking that function simultaneously.

For instance, for your case:-

//helper function to render title
const renderTitle = () => {
    return <strong>Name</strong>;
 };
//helper function to render value, you can also add styles to them via inline styles or using class or id.
const renderValue = () => {
  return (
    <pre style={{ marginLeft: 15 }}>
      {name === undefined ? "myName" : "myNames"}
    </pre>
  );
};
return (
  <div style={{ display: "flex" }}>
    <CustomComponent title={renderTitle()} value={renderValue()} />
    // invoking the helper functions to render the title and value
  </div>
);

Codesandbox Link - https://codesandbox.io/s/eloquent-resonance-h4m49

CodePudding user response:

You can pass prop Components in that following Example what I made for live view you can check here SandBox

import React, { useState } from 'react';
import { render } from 'react-dom';

const Success = () => {
  return <pre>Your state isn't undefined</pre>
}

const Undefined = () => {
  return <pre>Your state isn't undefined</pre>
}

const ReturnProp = ({propJSX}) => {
  return propJSX
} 

const App = () => {
  const [name, setName] = useState(undefined)

  return <ReturnProp propJSX={name===undefined? <Undefined />: <Success />}/>
}

render(<App />, document.querySelector('#app'));
  • Related