Negin
Negin

Reputation: 2394

Passing the value of a variable(string) from a razor view to a React component

I am wondering if you have any suggestions in regard to passing the string from a razor view to a React component?

export default class WidgetModel extends Component {

  constructor() {
    super()
  }

  render() {
    const {  } = this.props,   
    return (  
      <p>{Copy}</p>           
    )
  }
}
   <div id="widget">
      <p>@vm.Copy</p>
   </div>

Upvotes: 3

Views: 1867

Answers (1)

Milad
Milad

Reputation: 28592

As far as I understand, your c# code gets evaluated in the server and at that time, react doesn't exist, and then the code will be passed to the browser and then react will render it.

So basically you don't have access to your normal variables like you want, but It might be possible to assign your c# value to a global javascript variable so you can pick it up later in the browser :

Say this is your c# code :

<div id="widget">
      <p>@vm.Copy</p>
   </div>

add something like this :

<div id="widget">
      <p>@vm.Copy</p>

      <script>
        var window.Copy = "@vm.Copy"; // we need the quotation so javascript doesn't compile it as a refrence, rather as a string
        console.log('Copy',Copy);
      </script>
   </div>

and then in your react code your should be able to pick it up :

 render() {
    const {  } = this.props,   
    return (  
      <p>{window.Copy}</p>           
    )
  }

Upvotes: 4

Related Questions