Home > Software engineering >  Showing Strings which are there to completing the props
Showing Strings which are there to completing the props

Time:03-30

i have tried to render some element using props But it is showing Strings which are there to completing the props.

function Welcome(props){
const element = <p>
<h3>Hello {props.name}</h3>
<h3>My car Brand is {props.brand}</h3>
</p>
return element

}



function Greet() {
    const brand = "Ford";
    const welcome = <div>
        <Welcome name="World" />
        <Welcome brand={brand} />
    </div>
    return welcome;
}

Output is coming like this..

Hello World!! My car Brand is
Hello !!
My car Brand is Ford

but i wanted it as

Hello World!!
My car Brand is Ford

CodePudding user response:

don't need to sent brand explicitly in another function you can do it like this:

function Greet() {
    const brand = "Ford";
    const welcome = <div>
        <Welcome name="World" brand={brand}/>
    </div>
    return welcome;
}

and you can also return jsx directly

function Welcome(props) {
  return (
    <p>
      <h3>Hello {props.name}</h3>
      <h3>My car Brand is {props.brand}</h3>
    </p>
  );
}

function Greet() {
  const brand = 'Ford';
  return (
    <div>
      <Welcome name='World' />
      <Welcome brand={brand} />
    </div>
  );
}

that the actual way of doing it

CodePudding user response:

You're getting that output because you're calling your "Welcome" component twice, once with the "name" property and once with the brand property, so the first render is: 'Hello world!! My car Brand is [undefined because you didn't send the brand property] ' and the second rendering is : 'Hello!! [undefined because you didn't send the name property] My car Brand is Ford', to get the output you expect you should only call your "Welcome" component once with both properties like this:

<Welcome name={"World "} brand={brand}/>

I hope it helped you, and it's better to send JSX directly.

  • Related