0

I have one common component for Success and rendering this component through navigating routes.

SuccessComponent.jsx

var pageTitle;
const SuccessComponent = (props) => {
  pageTitle = props.location.state.title;
  return(
    <> jsx code here </> 
  )
}

//This title needs to be dynamic, not getting props here hence took var pageTitle but getting undefined.
let SuccessComp = withTitle({component: SuccessComponent, title: pageTitle})
export default SuccessComp;

WithTitle component is setting title through react-helmet library and updating on each screen. I need to change title on different calls of SuccessComponent. How can I achieve this?

I'm using SuccessComponent as below.

MyComponent.jsx

export default MyComponent = () => {
  const onSubmit = () => {
    props.history.push({pathname:'/success',state:{title: 'my comp'})
  }
  return(
    <> jsx code here </>
  )
}

MyComponent1.jsx

export default MyComponent1 = () => {
  const onSubmit = () => {
    props.history.push({pathname:'/success',state:{title: 'my comp 1'})
  }
  return(
    <> jsx code here </>
  )
}

withTitle.jsx

export default function withTitle({component: Component, title}){
 return function title(props){
  (
   <>
     <Helmet>
        <title>{title}</title>
     </Helmet>
     <Component {...props} />
   </>
   )
  }
}
Krina Soni
  • 870
  • 6
  • 14

2 Answers2

0

You are sending the state through the react-router but you try to access local props. You need to access the title in this.props.location.state.title

If you have a look at this answer it will help you get the right conslusion. How to pass params with history.push/Link/Redirect in react-router v4?

J.melendez
  • 43
  • 1
  • 7
0

withTitle.jsx

export default function withTitle({component: Component, title}){
const [titleState, setTitleState] = useState();

 return function title(props){
  (
   <>
     <Helmet>
        <title>{title}</title>
     </Helmet>
     <Component {...props} setTitle={setTitleState}/>
   </>
   )
  }
}

Added one method call and called it from Success Component as below.

SuccessComponent

const SuccessComponent = (props) => {
  props.setTitle(props.location.state.pageTitle);
  return(
    <> jsx code here </> 
  )
}

//This title needs to be dynamic, not getting props here hence took var pageTitle but getting undefined.
let SuccessComp = withTitle({component: SuccessComponent })
export default SuccessComp;
Krina Soni
  • 870
  • 6
  • 14