I am importing ReactJS via CDN links into a huge existing PHP project (latte templates). So it is not a classic ReactApp. And I would like to play with it and see the options of React when used this way.
So far pretty good. But I would like to know if it is possible to pass props/data to a component generated this way? Have anybody here had some experience with it?
My latte code:
<div id="react_container"></div>
My js code:
'use strict'
const e = React.createElement
const { useState } = React
const ReactFun = () => {
const [color, setColor] = useState('')
const changeColor = () => {
const newColor = color == 'black' ? '#1E88E5' : 'black'
setColor(newColor)
}
return (
<div className='pb-5 d-flex gap-regular'>
<h4 className='mb-3' style={{ color: `${color}` }}>
Magic
</h4>
<div className='btn btn-outline-primary' onClick={changeColor}>
<span>Click to change color</span>
</div>
</div>
)
}
const domContainer = document.querySelector('#react_container')
const root = ReactDOM.createRoot(domContainer)
root.render(e(ReactFun))
I found old solutions for class components here: How to pass server data into React component, so I guess there is a way, but I am trying now for hours and I can’t figure out how to pass anything into my component written this way.. has anyone any idea?
I would like to achieve something like this with a color for example:
<div id="react_container" data-defaultColor="red"></div>
const e = React.createElement
const { useState } = React
const ReactFun = ({defaultColor}) => {
const [color, setColor] = useState(defaultColor)
const changeColor = () => {
const newColor = color == 'black' ? '#1E88E5' : 'black'
setColor(newColor)
}
return (
<div className='pb-5 d-flex gap-regular'>
<h4 className='mb-3' style={{ color: `${color}` }}>
Magic
</h4>
<div className='btn btn-outline-primary' onClick={changeColor}>
<span>Click to change color</span>
</div>
</div>
)
}
const domContainer = document.querySelector('#react_container')
const root = ReactDOM.createRoot(domContainer)
root.render(e(ReactFun))
here are the cdn links I am using now:
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>