where does input to function come from - reactjs

We have the following react html. In the callback function filterList() we have as a parameter 'input' filterList(input). Where does this object come from? Is this coming from the onClick event? what other objects are available?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Filtered List</title>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<div id='container'></div>
<script type="text/jsx">
class FilteredList extends React.Component {
constructor(props) {
super(props);
var allItems = [ "anteater", "bear", "cat", "dog", "elephant", "fox" ];
this.state = { initialItems: allItems, currentItems: allItems };
}
filterList(input){
var updatedList = this.state.initialItems;
updatedList = updatedList.filter(function(item){
return item.search(input.target.value) !== -1;
});
this.setState({currentItems: updatedList});
}
render(){
console.log(this);
return (
<div className="filter-list">
<input type="text" placeholder="Filter" onChange={this.filterList.bind(this)}/>
<List items={this.state.currentItems}/>
</div>
);
}
};
class List extends React.Component {
render(){
return (
<ul> { this.props.items.map(function(item) {
return <li key={item}>{item}</li> }) }
</ul>
)
}
};
ReactDOM.render(<FilteredList/>, document.getElementById('container'));
</script>
</body>
</html>

Input has an onChange listener when something happens it gives parameter to the function of the onChange.
Without this parameter the onChange parameter can't know what changed :)
Few words: yes it comes from onChange
More on here https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange

Related

Passing a JSON as prop in component React JS

I have a component with another child component and I am passing a JSON state variable of the parent component as prop to the child component, but when I modify the JSON in the child component the state variable of the parent is been modified too. It doesn't have sense beacuse it just happens with JSON props, but if i use strings, numbers or arrays it works good and child state variables are just modified.
These are my components:
class Child extends React.Component{
constructor(props){
super(props)
this.state={
test2: this.props.data,
}
this.changeTextField = this.changeTextField.bind(this)
}
changeTextField(e){
let data = this.state.test2
data['name'] = e.target.value
this.setState({test2: data})
}
render(){
return(
<div>
<input type="text" value={this.state.test2['name']} onChange={this.changeTextField}/>
</div>
)
}
}
class Parent extends React.Component{
constructor(props){
super(props)
this.state={
test: {name: "hola"},
editing: false,
}
this.edit = this.edit.bind(this)
this.cancel = this.cancel.bind(this)
}
edit(){
this.setState({editing: true})
}
cancel(){
this.setState({editing: false})
}
render(){
return(
<div>
{(this.state.editing) ?
<React.Fragment>
<Child data={this.state.test}/>
<button onClick={this.cancel}>cancelar</button>
</React.Fragment>
:
<React.Fragment>
<h1>{this.state.test['name']}</h1>
<button onClick={this.edit}>edit</button>
</React.Fragment>
}
</div>
)
}
}
$(document).ready(function(){
ReactDOM.render(<Parent/>, document.getElementById("app"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script src="parent.jsx" type="text/babel"></script>
</body>
</html>
This is how JavaScript works with Objects. They are always passed by reference and the others (strings, booleans, numbers as you mentioned) are primitives meaning they are immutable.
There are many amazing answers on SO already regarding these:
JavaScript by reference vs. by value
Is JavaScript a pass-by-reference or pass-by-value language?
How do we get around this?
In your snippet, where you say data['name'] = e.target.value you are still mutating the state object, which is surely a Not To Do in React. You can read upon Power of not mutating content in React Docs.
You could create a copy of the test2 and choose to mutate that instead:
const data = {...this.state.test2};
data['name'] = e.target.value
But there is a chance that this function gets called programatically, this will run into an error because setState is async. Instead it gives us a functional version to deal with:
this.setState(prevState => ({
test2: {
...prevState.test2,
name: value,
}
}));
Full Demo:
class Child extends React.Component{
constructor(props){
super(props)
this.state={
test2: this.props.data,
}
this.changeTextField = this.changeTextField.bind(this)
}
changeTextField(e){
const value = e.target.value
this.setState(prevState => ({
test2: {
...prevState.test2,
name: value,
}
}))
}
render(){
return(
<div>
<input type="text" value={this.state.test2['name']} onChange={this.changeTextField}/>
</div>
)
}
}
class Parent extends React.Component{
constructor(props){
super(props)
this.state={
test: {name: "hola"},
editing: false,
}
this.edit = this.edit.bind(this)
this.cancel = this.cancel.bind(this)
}
edit(){
this.setState({editing: true})
}
cancel(){
this.setState({editing: false})
}
render(){
return(
<div>
{(this.state.editing) ?
<React.Fragment>
<Child data={this.state.test}/>
<button onClick={this.cancel}>cancelar</button>
</React.Fragment>
:
<React.Fragment>
<h1>{this.state.test['name']}</h1>
<button onClick={this.edit}>edit</button>
</React.Fragment>
}
</div>
)
}
}
$(document).ready(function(){
ReactDOM.render(<Parent/>, document.getElementById("app"))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script src="parent.jsx" type="text/babel"></script>
</body>
</html>

why hexadecimal codes don't display in reactjs

👍 and 👎 codes work in plain html. How do I get them to work in react?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Like Click</title>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<div id='container'>
</div>
</body>
</html>
<script type='text/jsx'>
class Like extends React.Component{
constructor(props){
super(props);
this.state={liked:false};
}
toggle(){
this.setState({liked: !this.state.liked});
}
render(){
var name = this.props.name;
var txt = this.state.liked ? 'Like':'Unlike';
var weight = this.state.liked ? 'bold':'normal';
var color = this.state.liked ? 'green':'red';
var thumb = this.state.liked ? "👍":"👎";
return(
<div>
<span style={{fontWeight:weight,color:color}} onClick={this.toggle.bind(this)}> {name} {thumb}{txt} </span>
</div>
);
}
}
ReactDOM.render(
<Like name='Java' />,document.getElementById('container')
);

How to fix the beginner's ReactJS error?

I'm beginner in ReactJS and am trying to run the following code:
#{
ViewBag.Title = "Index";
}
<h2>Hello World-React JS</h2>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/javascript">
var HelloWorldComponent = React.createClass({
getInitialState: function () {
return {
serverMessage: ''
};
},
componentDidMount: function () {
$.get('/Home/getmessage', function (result) {
if (this.isMounted) {
this.setState({
serverMessage: result
});
}
}.bind(this));
},
render: function () {
return ("<h1>{this.state.serverMessage}</h1>");
}
});
ReactDOM.render(<HelloWorldComponent />, document.getElementById("helloworldcontainer"));
</script>
<div id="helloworldcontainer"></div>
As you can see this is VS2017 MVC simple test application.
Actually, in VS editor I have some complaints that is shown on the screen shot bellow:
How to fix it and run it?
Change your script type as <script type="text/babel">
sample code :
<html>
<head>
<title>demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
</head>
<body>
<div id="container"/></div>
<script type="text/babel">
class MessageBox extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<div className={`messageBox ${this.props.type} || hidden`}>
{this.props.message}
</div>
</div>
);
}
}
class NameInput extends React.Component {
constructor(props) {
super(props);
this.state = {
message: {
type: "success",
body: "Now my message is in NameInput's state"
}
}
this.buttonClicked = this.buttonClicked.bind(this);
}
buttonClicked(evt) {
alert("hi");
}
render() {
let msg = this.state.message;
return (
<div>
<label>Name: <input type="text" /></label>
<button onClick={this.buttonClicked}>Click me!</button>
<MessageBox type={msg.type} message={msg.body}/>
</div>
)
}
}
ReactDOM.render(
<NameInput />,
document.getElementById('container')
);
</script>
</body>
</html>
Hope this helps.
as #Adeel Imran suggests, For just checking how react works, this is fine. For future development use babel-cli and try to write a component in a separate file.

Calling a function in a file with jsx code in a js file

I have three files, percentGuageWidget.js, index.html, and main.js
percentGuageWidget.js has some react.js & jsx code
I am getting renderWidget is not defined. It seems if I call renderWidget in the percentGuageWidget.js, it works fine, but it won't work when called elsewhere.
How do I make it so I can call it from outside of that file.
class PercentGuageWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 0
}
}
componentDidMount() {
var widget = this;
setInterval(function(){
widget.setState({value:Math.round(Math.random()*100)});
}, 1000)
}
/* The render will be updated whenever state changes are made to the widget */
render() {
return (
<div className="percent-guage-widget widget">
<div className="bar" style={{width:this.state.value + "%"}}></div>
<div className="amount">{this.state.value}%</div>
</div>
);
}
}
var container = document.getElementById('target-widget-container');
function renderWidget(){
ReactDOM.render(<PercentGuageWidget />, container);
}
<html>
<head>
<script> var appGlobals = {} </script>
<script
src="http://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="target-widget-container"></div>
</body>
<script src="https://unpkg.com/react#15.0.1/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15.0.1/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/babel" src="widgets/percentGaugeWidget.js"></script>
<script>renderWidget();</script>
</html>

Trying To Get User Data From GitHub API Not Sure What's Wrong

I Wrote A Peace Of Code Which If Works Expected To Get Profile Pic And User Name From GitHub API According To User Input. Console Also Not Showing Any Error.Can Any One Help Me Correct This Thanks In Advance .
This I What I Tried So Far
var Main = React.createClass({
getInitialState:function(){
return({
user:[]
});
},
addUser: function(loginToAdd) {
this.setState({user: this.state.logins.concat(loginToAdd)});
},
render: function() {
var abc = this.state.user.map(function(user){
return(
<Display user={user} key={user}/>
);
});
return (
<div>
<Form addUser={this.addUser}/>
{abc}
<hr />
</div>
)
}
});
var Form = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var loginInput = React.findDOMNode(this.refs.login);
this.props.addUser(loginInput.value);
loginInput.value = '';
},
render:function(){
return (
<div onSubmit={this.handleSubmit}>
<input type="text" placeholder="github login" ref="login"/>
<button>Add</button>
</div>
)
}
});
var Display = React.createClass({
getInitialState:function(){
return{};
},
componentDidMount:function(){
var component = this;
$.get("https://api.github.com/users/"+this.props.user,function(data){
component.setState(data);
});
},
render: function() {
return (
<div>
<img src={this.state.avatar_url} width="80"/>
<h1>{this.state.name}</h1>
</div>
)
}
});
ReactDOM.render(<Main />, document.getElementById("app"));
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="demo.css">
</head>
<body>
<div class="container">
<div id="app"></div>
</div>
<script src="demo.js" type="text/babel"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.min.js"></script>
</body>
</html>
JSBin Link
div do not have an onSubmit event form do however, fix that and you should be ok

Resources