user3552178
user3552178

Reputation: 2971

How to pass props from html div to the function component in react?

Don't know how to pass properties from html into react file. This is the existing code,

<html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>

<body>

<div id="mydiv" parm="some info"></div>
<script type="text/babel" src="h2.js"></script>

</body>
</html>

The react file, i'm manually sending props "parm={2}" for now.

const Hello = (props) => {
        console.log(props);
        return (<h2>h2 with function component {props.parm}</h2>);
}

ReactDOM.render(<Hello parm={2} />, document.getElementById('mydiv'));

My Q is, how to pass parm from html to Hello() component ? Pls note, i have to turn off CORS for local testing, https://alfilatov.com/posts/run-chrome-without-cors/

Upvotes: 2

Views: 1629

Answers (2)

Jordan Rolph
Jordan Rolph

Reputation: 1358

Sure, it's possible.

Note: I'm not sure what your use-case is. Maybe you are "sprinking" react into an existing project? If you are not, I'd suggest you take a look at the React docs as they might suggest a better way to achieve your outcome.

Anyway, here's an example that implements what you have asked. Notice your HTML param is logged to the console. You can then use it inside react.

https://codesandbox.io/s/params-to-react-from-html-lycqx?fontsize=14&hidenavigation=1&theme=dark

// here's how to get the value itself
const myParam = document
    .querySelector("#my_container") // get the html element, e.g. a div
    .getAttribute("myParam"); // get the value of the custom property on that element

Hope it helps!

Upvotes: 2

Mahipat Jadav
Mahipat Jadav

Reputation: 1

React is not designed to behave in that way, HTML div you are using is the root element and all component is going to render in that. so you can not pass. but in first place why you want to do that. there are other ways to use global values inside of react component.

Not ideal solution but you can use global scope to get the value inside, or else create separate service to store values and then import that inside react component.

Upvotes: 0

Related Questions