How to update different component textbox value in React js..? - javascript

Environment
OS : Windows 7 - 64 bit
Framework : CodeIgniter PHP MVC
JS: React Js
I am having two different components LeftComponent and RightComponent which is merged by MergeLeftRightComponent.
MainApp which is responsible for rendering.
Having textbox in LeftComponent and RightComponent. While changing value in left textbox, i need to update value in right textbox and vice-versa.
How to achieve this..?
Framed this app from the basics of codeofaninja tutorial.
My app sample view
Codes
view.php
<!DOCTYPE html>
<head>
<title>React page</title>
</head>
<body>
<div class='task-container' id='task-container'>
</div>
<!-- react js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<!-- react components -->
<script type="text/babel" src="<?php echo base_url('assets/js/components/right.component.js');?>"></script>
<script type="text/babel" src="<?php echo base_url('assets/js/components/left.component.js');?>"></script>
<script type="text/babel" src="<?php echo base_url('assets/js/components/merge.component.js');?>"></script>
<script type="text/babel" src="<?php echo base_url('assets/js/components/main.component.js');?>"></script>
<!-- jQuery library required by bootsrap js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
main.component.js
var MainApp = React.createClass({
render: function(){
var modeComponent = <MergeLeftRightComponent changeAppMode={this.changeAppMode} />;
return modeComponent;
}
});
ReactDOM.render(<MainApp />,document.getElementById('task-container'));
merge.component.js
window.MergeLeftRightComponent = React.createClass({
getInitialState: function() {
return {
inputVal:"",
};
},
changeinputVal: function(e) {
this.setState({
inputVal: e.target.value,
});
},
render: function() {
return (
<div className='task-container'>
<LeftComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
<RightComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
</div>
);
}
});
left.component.js
window.LeftComponent = React.createClass({
getInitialState: function(){
return {
task_name:"Mountain task"
};
},
handleChange: function(e){
this.setState({
inputVal:e.target.value
});
},
render: function() {
return(
<div className="left-box">
<div className="info-container">
<input type="text" className="task-name form-control" value={this.props.task_name} onChange={this.handleChange}/>
</div>
</div>
);
}
});
right.component.js
window.RightComponent = React.createClass({
getInitialState: function(){
return {
task_name:"Mountain task"
};
},
handleChange: function(e){
this.setState({
inputVal:e.target.value
});
},
render: function() {
return(
<div className="right-box">
<div className="info-container">
<input type="text" className="task-name form-control" value={this.props.task_name} onChange={this.handleChange}/>
</div>
</div>
);
}
});
Help me to achieve this.
Thanks in Advance..

in the merge.component.js file you need to bind changeinputVal function
In left.component.js call changeinputVal function at your input function
handleChange: function(e){
this.setState({
inputVal:e.target.value
});
this.props.onChange(e);
},
merge.component.js file
class MergeLeftRightComponent extends React.Component {
constructor(props) {
super(props);
this.changeinputVal = this.changeinputVal().bind(this);
}
getInitialState() {
return {
inputVal: ""
};
}
changeinputVal(e) {
this.setState({
inputVal: e.target.value
});
}
render() {
return (
<div className='task-container'>
<LeftComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
<RightComponent inputVal={this.state.inputVal} onChange={this.changeinputVal}/>
</div>
);

Related

How to use google translator with flags in nextjs

I am new in Reactjs and trying to integrate "google translator with flags",I have following code
which is working fine (html + javascript code) and giving me exactly output as i want but how can i use this
code in "nextjs/react" (index.js page)?
<html>
<head id="Head1" runat="server">
<title>Google Translation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/css/bootstrap-select.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.5.0/css/flag-icon.min.css" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="google_translate_element" style="display: none;"></div>
<select class="selectpicker" data-width="fit" onchange="translateLanguage(this.value);">
<option data-content='<span class="flag-icon flag-icon-us"></span> English' value="English">English</option>
<option data-content='<span class="flag-icon flag-icon-fr"></span> French' value="French">French</option>
<option data-content='<span class="flag-icon flag-icon-es"></span> Spanish' value="Spanish">Spanish</option>
</select>
<div>
This is just a table.
</div>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/js/bootstrap-select.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false }, 'google_translate_element');
}
function translateLanguage(lang) {
googleTranslateElementInit();
var $frame = $('.goog-te-menu-frame:first');
//alert('value is ' +lang);
if (!$frame.size()) {
alert("Error: Could not find Google translate frame.");
return false;
}
$frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
return false;
}
$(function(){
$('.selectpicker').selectpicker();
});
</script>
</body>
</html>
I tried but giving me following error
"Hydration failed because the initial UI does not match what was rendered on the server"
Update answer:
import React, { useEffect, useState, useRef } from "react";
export default function IndexPage() {
function translateLanguage(lang) {
googleTranslateElementInit();
const frame = document.getElementsByClassName("goog-te-menu-frame")[0];
if (!frame) return;
const items = frame.contentDocument.documentElement.querySelectorAll(
".goog-te-menu2-item"
);
items.forEach((element) => {
if (lang == element.getElementsByTagName("span")[1].innerText)
element.click();
});
return false;
}
function googleTranslateElementInit() {
if (!google) return;
new (google.translate.TranslateElement)(
{
pageLanguage: "en",
layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
autoDisplay: false
},
"google_translate_element"
);
}
useEffect(() => {
let script = document.createElement("script");
script.src = `https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit`;
document.body.insertBefore(script, document.body.childNodes[0]);
}, []);
return (
<div>
<div id="google_translate_element" style={{ display: "none" }} />
<CustomSelect onChange={translateLanguage} />
<div>This is just a table.</div>
</div>
);
}
const CustomSelect = ({ onChange }) => {
const [lang, setLang] = useState(LANGS[0]);
const [isShow, setIsShow] = useState(false);
const ref = useRef(null);
useClickOutside(ref, () => setIsShow(false));
return (
<div className="w-24 cursor-pointer relative">
<div onClick={() => setIsShow(true)} ref={ref}>
<span className={`flag-icon ${lang.icon}`} /> {` ${lang.name}`}
</div>
<div
className={`border border-b-0 absolute top-6 left-0 bg-white ${!isShow && "hidden"
}`}
>
{LANGS.map((lang, index) => (
<div
key={index}
className="border-b"
onClick={() => {
setLang(lang);
onChange(lang);
}}
>
<span className={`flag-icon ${lang.icon}`} />
{` ${lang.name}`}
</div>
))}
</div>
</div>
);
};
const LANGS = [
{
name: "English",
icon: "flag-icon-us"
},
{
name: "French",
icon: "flag-icon-fr"
},
{ name: "Spanish", icon: "flag-icon-es" }
];
const useClickOutside = (ref, callback) => {
const handleClick = (e) => {
if (ref.current && !ref.current.contains(e.target)) {
callback(e);
}
};
React.useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
You can check in codesandbox

Simple React Snippet Not Working

Hi There I am new to react,
I am trying to run this trivial snippet but it's not working:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.2.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.25/browser-polyfill.min.js"></script>
</head>
<body>
<div id="app_root"></div>
<script type="text/babel">
var Hello = React.createClass({
render: function() {
return(
<div>Hello World!</div>
);
}
});
ReactDOM.render(<Hello />, document.getElementById("app_root"));
</script>
</body>
console do not show any error messages and I do not get any output after running the script
As alluded to in the other answers, it's because JSX needs babel. In your case it is simply a matter of including babel and not just the browser-polyfill:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.2.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.25/browser-polyfill.min.js"></script>
</head>
<body>
<div id="app_root"></div>
<script type="text/babel">
var Hello = React.createClass({
render: function() {
return(
<div>Hello World!</div>
);
}
});
ReactDOM.render(<Hello />, document.getElementById("app_root"));
</script>
</body>
If you do not want to use JSX, Babel ... you have to replace the JSX definition <Hello /> by React.createElement(Hello, null, null)
I did not test the following code but in my eyes this should be correct:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.2.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.25/browser-polyfill.min.js"></script>
</head>
<body>
<div id="app_root"></div>
<script>
var Hello = React.createClass({
render: function() {
return React.createElement('div', null, `Hello World`);
}
});
ReactDOM.render(React.createElement(Hello, null, null),
document.getElementById("app_root"));
</script>
</body>
Codepen version works fine: https://codepen.io/svitch/pen/ypPLwN
That means your problem is Babel script. I agree with #bmceldowney - polyfill version is not enough, just include the regular version from cdnjs.
Also you can write simple "Hello World" without Babel:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.2.0/react-dom.min.js"></script>
</head>
<body>
<div id="app_root"></div>
<script>
var element = React.createElement(
'div',
null,
'Hello World'
)
ReactDOM.render(
element,
document.getElementById('app_root')
);
</script>
</body>
</html>

How can I add component (without import/export to html) in React variable global

How can I add component (without import/export to html) in React variable global
Example
//HTML
<body>
<div id="App"></div>
<script src="https://unpkg.com/react#15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15.3.2/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-core#5.8.38/browser.min.js"></scrip
<script>
var App, Search
</script>
<script type="text/babel" src="component/App.js"></script>
<script type="text/babel" src="component/Search.js"></script>
</body>
//App.js
var App = React.createClass({
render: function() {
var styles = {
margin: '0 auto',
border: '1 px solid red',
width: '50%'
};
return (
<div style={styles}>
<h1>sdadasssd!</h1>
<p>fgfgfgfggf</p>
</div>
);
}
});
//Search.js
var Search = React.createClass({
render: function() {
var styles = {fontSize: '1.5em', width: '90%', maxWidth: '350px'};
return <input
type="text"
placeholder="gfgff"
style={styles}
/>
}
});
How can I add component (without import/export to html) in React variable global
If by add you mean render to html, use:
ReactDOM.render(
<App />,
document.getElementById('App')
);
Demo:
var App = React.createClass({
render: function() {
var styles = {
margin: '0 auto',
border: '1 px solid red',
width: '50%'
};
return (
<div style={styles}>
<h1>sdadasssd!</h1>
<p>fgfgfgfggf</p>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('App')
);
<div id="App"></div>
<script src="https://unpkg.com/react#15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15.3.2/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-core#5.8.38/browser.min.js">
<script>
var App, Search
</script>
<script type="text/babel" src="component/App.js"></script>

Getting error near div tag

I am new to react js..
When i run it i am getting syntax near tag i don't know why.. :(
<script type="text/babel">
var movie = react.createClass({
render:function(){
return{
<div>
<h1>{this.props.movietitle}</h1>
<h3>{this.props.moviegenre}</h3>
</div>
};
}
});
ReactDOM.render(
<div>
<movie movietitle="Avatar" moviegenre="Action" />
</div>,document.getElementById('takevalue'));
</script>
Your should have () for wrapping the return. Not the {}. And React components must be capitalized(<Movie/>)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="takevalue"></div>
<script type="text/babel">
var Movie = React.createClass({
render:function(){
return(
<div>
<h1>{this.props.movietitle}</h1>
<h3>{this.props.moviegenre}</h3>
</div>
)
}
})
ReactDOM.render(
<div>
<Movie movietitle="Avatar" moviegenre="Action" />
</div>,document.getElementById('takevalue'));
</script>
You need Babel to convert jsx into js.
Hope this helps!

React does not render

My react code does not seem to be working. I have the following html:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
</head>
<body>
<div id="example"></div>
<form id="frm1" action="form_action.asp">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit" class="btn-primary">
</form>
<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>
<script type="text/babel" src="helloworld.js"></script>
</body>
</html>
and the following react code
helloworld.js:
var Comment = React.createClass({
render: function(){
return(
<div>
<div className="commentText">Some Comment</div>
<button onClick="">Edit</button>
<button onClick="">Remove</button>
</div>
);
}
});
function myFunction() {
alert("hello world");
}
ReactDOM.render(
<Comment />,document.getElementById('example')
);
But it does neither spit out the comment in the example div, nor does it call the function for the input field. I suspect there is something wrong with my React setup in general, which is why I post both things here at the same time. However, the build folder and the referenced files do all exist.
It works, check this link out.
var Comment = React.createClass({
render: function(){
return(
<div>
<div className="commentText">Some Comment</div>
<button onClick="">Edit</button>
<button onClick="">Remove</button>
</div>
);
}
});
function myFunction() {
alert("hello world");
}
ReactDOM.render(
<Comment />,document.getElementById('example')
);
Make use of webpack to transpile your code since babel-browser has been removed.see this Also react onClick event function can be defined in the react component itself in helloworld.js like
var Comment = React.createClass({
handleClick: function() {
alert("hello world");
}
render: function(){
return(
<div>
<div className="commentText">Some Comment</div>
<button onClick={this.handleClick()}>Edit</button>
<button onClick="">Remove</button>
</div>
);
}
});
function myFunction() {
alert("hello world");
}
ReactDOM.render(
<Comment />,document.getElementById('example')
);
To set up webpack follow this link. Its easy to follow

Categories