function energy_lab3_output_root() {
$url = get_field( 'energy_data_url', 'option' );
if ( ! $url ) {
$today = date('Y-m-d');
$url = "https://api.open-meteo.com/v1/forecast?"
. "latitude=50.45&longitude=30.523"
. "¤t_weather=true"
. "&timezone=Europe%2FKiev";
}
return
'<div id="react-root-3"></div>'
. '<span id="acf-energy-url" style="display:none;">'
. esc_url( $url )
. '</span>';
}
add_shortcode( 'energy_lab3_root', 'energy_lab3_output_root' );
function energy_lab3_enqueue_no_babel() {
wp_enqueue_script(
'react',
'https://unpkg.com/react@18/umd/react.development.js',
array(),
null,
true
);
wp_enqueue_script(
'react-dom',
'https://unpkg.com/react-dom@18/umd/react-dom.development.js',
array( 'react' ),
null,
true
);
wp_enqueue_script(
'lab3-data-passing',
get_stylesheet_directory_uri() . '/js/lab3-data-passing.js',
array( 'react', 'react-dom' ),
null,
true
);
}
add_action( 'wp_enqueue_scripts', 'energy_lab3_enqueue_no_babel' );document.addEventListener('DOMContentLoaded', function() {
var mount = document.getElementById('react-root-3');
if (!mount) return;
var e = React.createElement;
// Child component: fetches and shows temperature
function EnergyDataDisplay(props) {
var dataState = React.useState(null),
temperature = dataState[0],
setTemperature = dataState[1];
var errorState = React.useState(null),
error = errorState[0],
setError = errorState[1];
React.useEffect(function() {
fetch(props.url)
.then(function(res) {
if (!res.ok) throw new Error(res.status + ' ' + res.statusText);
return res.json();
})
.then(function(json) {
if (
json.current_weather &&
typeof json.current_weather.temperature === 'number'
) {
setTemperature(json.current_weather.temperature);
} else {
throw new Error('No current_weather.temperature in response');
}
})
.catch(function(err) {
setError(err);
});
}, [props.url]);
if (error) {
return e(
'p',
{ style: { color: 'red', textAlign: 'center' } },
'Error fetching data: ' + error.message
);
}
if (temperature === null) {
return e(
'p',
{ style: { textAlign: 'center' } },
'Loading temperature…'
);
}
return e(
'div',
{ style: { textAlign: 'center', fontFamily: 'Arial, sans-serif' } },
e('h4', null, 'Current Temperature:'),
e(
'p',
null,
e('strong', null, temperature + ' °C')
)
);
}
// Parent component: reads URL and mounts child
function EnergyDataDashboard() {
var span = document.getElementById('acf-energy-url'),
url = span ? span.textContent.trim() : '';
return e(
'div',
{
style: {
border: '1px solid #444',
padding: '20px',
borderRadius: '5px',
maxWidth: '400px',
margin: '20px auto',
backgroundColor: '#fafafa'
}
},
e(
'h2',
{ style: { textAlign: 'center', fontFamily: 'Arial, sans-serif' } },
'Energy Data Dashboard (Lab 3)'
),
e(EnergyDataDisplay, { url: url })
);
}
ReactDOM.createRoot(mount).render(
e(EnergyDataDashboard)
);
});