0

I am currently in the Post component, and fetch data through Fetch Api from "/home" route.

 componentDidMount() {
   fetch('/home')
     .then(res => res.json())
     .then((data)=> {
       console.log(data.ports)
       this.setState({ports: data.ports})
     })
     .catch(error =>console.log(error))
 }

Changing the response to json data, and set the state to be data.port_symbols. But now I want to use the data in the state to be the URL parameter, so I try the following code.

render() {   
return (
  <div>
    <h2>ports</h2> 
    <ul>
      {this.state.ports.map((port, index)=>          
         <li>
           <NavLink activeClassName='active-link' 
            to='/get_info/${port[0]}/${port[1]}'key={index}>
             {port[0]}/{port[1]}
           </NavLink>             
        </li>          
         )
      }   
    </ul> 

So the question is, {port[0]}/{port[1]} can be transferred into the value which stored in the state, but ${port[0]}/${port[1]} can not be transferred into the value into the URL, the URL just displays $%7Bport[0]/$%7Bport[1]%7D%7D.

Can anyone help to figure out what the problem is and help to solve it? Thank you.

1
  • to='/get_info/${port[0]}/${port[1]}' these should be back ticks, not apostrophes Commented Nov 4, 2019 at 17:33

1 Answer 1

3

I think you just need to make this a template string:

   <NavLink activeClassName='active-link' 
    to=`/get_info/${port[0]}/${port[1]}` key={index}>
     {port[0]}/{port[1]}
   </NavLink> 

the back ticks "`" will allow you to use the ${variable} syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.