Home > Blockchain >  ReactJS <select> if value is selected from database
ReactJS <select> if value is selected from database

Time:12-28

I've tried to googling this but not luck. I'm new in ReactJS (previously PHP)

So I have table like this:

id is_active
1 1
2 0
3 1

Then usually in PHP I can do this for <select> option

<select  name="is_active">
    <option value="1" <?php if(@$row['is_active']==1) { echo 'selected'; } ?>>Active</option>
    <option value="0" <?php if(@$row['is_active']==0) { echo 'selected'; } ?>>Inactive</option>
</select>

But how to do this on React?

I created this on React:

const {id} = useParams();
 
const [data, getData] = useState([]);
const [errorMessage, setErrorMessage] = React.useState([]);

axios.get(`http://localhost:5666/user/${id}`)
.then((result) => {         
    if (result.data.message === 'OK') {
        getData(result.data.data)
    }else{
        setErrorMessage(result.data.message);
    }
})

And I am able to retrieve its data like this on type:

<input type="text" name="username" className="form-control" value={item.username}  />

But when I want to do if the option is same with database, tried this method but it was not working:

<option value={item.is_active} selected={optionsState == option.value}>{option.is_active}</option>

Please help, thanks in advance.

CodePudding user response:

You can't call database directly in React.

You should call API by using useEffect and const a state to save the values.

CodePudding user response:

// Let's see you have any component

function Select({
  selected,
  data,
  onChange
}) {
  return (
    <select value={selected} onChange={onChange}>
      {data.map(i => <option value={i.value}>{i.label}</option>)}
     </select>
    )
}
export default Select;


function App {
  const [data, setData] = React.useState();
  const [selected, setSelected] = React.useState({});
  React.useEffect(() => {
    // call api 

    // set data to state
  }, [])
  
  const onChange=(event)=> {
    const {name, value} = event.target;
    console.log({name, value});
  }
  return (<Select data={data} selected={selected.value}/>)
};

ReactDOM.render( < App / > , document.getElementById('app'))

  • Related