Nando
Nando

Reputation: 103

Overwriting react component when using it

I was wondering if I can change a React's component when I need to do a tiny change instead of creating a brand new.

Lets say that I have declared a component like that:

const ReactComp = ()=> {
return (
 <div>

 <h1>Hello</h1>

  <h3>Hi, I am a component</h3>

  <p>I am a paragraph</p>

</div>
}

export default ReactComp

Page 1

import ReactComp from "../ReactComp.js


<  ReactComp />

Page 2

import ReactComp from "../ReactComp.js


<  ReactComp />

In page1 I am happy with all components being rendered, but in page 2 I don't want the paragraph " I am a paragraph " to be there. I know there is an easy way to do that by declaring props.text and later just declaring text in the ReactComp in "page 1" and leaving the props blank in "page 2". But this was just an example. In the real code the paragraph that I dont want to show in "page2" is a complex function with a lot of variables declared in the ReactComp.js page.

I hope this is clear enough (I know is a bit confusing) but what I am looking for is a magical way to render ReactComp in another page without the paragraph. An easy way to do small changes in a react component when using it in another page.

Upvotes: 0

Views: 43

Answers (2)

kJs0
kJs0

Reputation: 138

There's a couple things you could do for this in terms of props to pass the component:

The below methods will use destructuring of props and ES6 syntax along with conditional rendering based on a null check (or boolean value).

Null check:

const ReactComp = ({ paragraph }) => {
return (
 <div>

 <h1>Hello</h1>

  <h3>Hi, I am a component</h3>

  {paragraph && (
  <p>{paragraph}</p>)}

</div>
}

export default ReactComp

--------- (Where this component is used)

<ReactComp paragraph='some text' /> // will show paragraph with 'some text'
<ReactComp /> // will not show paragraph

Boolean prop:

const ReactComp = ({ showParagraph }) => {
return (
 <div>

 <h1>Hello</h1>

  <h3>Hi, I am a component</h3>

  {showParagraph && (
  <p>I am a paragraph</p>)}

</div>
}

export default ReactComp

--------- (Where this component is used)

<ReactComp showParagraph /> // will show paragraph (can also use showParagraph={true})
<ReactComp showParagraph={false} /> // will not show paragraph

Some educational resources on some topics above:

Upvotes: 1

Milad Ahmadi
Milad Ahmadi

Reputation: 29

you must pass props to your component for render component with your customization

Upvotes: 0

Related Questions